search

Home  >  Q&A  >  body text

node.js - mongo更新嵌套结构中的内容

一个questions表,存所有的问题,每一个question有一个answers的key,是个数组对象,每个answer有自己_id和一个up属性,现在想通过这个_id来更新up属性。
请问前辈们如何做?试了很多都没办法正确更新,谢谢qaq

PHP中文网PHP中文网2754 days ago584

reply all(3)I'll reply

  • 怪我咯

    怪我咯2017-05-02 09:28:29

    db.questions.update({
        "answers._id": ObjectId("58f575ca09c601c45f6c281a")
    }, {
        $set: {
            "answers.$.up": 1
        }
    });
    

    Note the $ operator, we call it Positional Operator, please see the link for more information.

    reply
    0
  • 滿天的星座

    滿天的星座2017-05-02 09:28:29

    I think you shouldn’t nest the data table so deeply. I think it’s more reasonable to build a relational table.

    reply
    0
  • 过去多啦不再A梦

    过去多啦不再A梦2017-05-02 09:28:29

    Okay, assuming you know the index of the answer you want to modify in the answers array, you can use question.answers.index.up to update it. If you don’t know the index now, you can use $ to place it, and use {answers._id for Filter. :123456} update using {answers.$.up:321}

    reply
    0
  • Cancelreply