嵌套文档更新MongoDB

时间:2017-05-24 22:04:17

标签: mongodb

{ 
    "_id" : ObjectId("5925e2213daf48359cb5429e"), 
    "email" : "test3@gmail.com", 
    "firstname" : "test3", 
    "friends" : [
        {
            "friend_email" : "test2@gmail.com", 
            "status" : 1, 
            "fname" : "test2"
        },
        {
            "friend_email" : "test1@gmail.com", 
            "status" : 1, 
            "fname" : "test1"
        }
    ]
}

我的数据库如上所示。 “朋友”里面可以有很多条目。我必须使用(假设)friend_email =“test2@gmail.com”和email =“test3@gmail.com”搜索特定条目(取决于变量值)并将其特定字段“status”更改为0。 我已经写了以下更新查询,

collection_temp.update({

        "email": email(test3@gmail.com) ,     
        "friends" :
         {$elemMatch : 
                 {"friend_email" : friend_req_sent_to (test2@gmail.com)}
         }},
         {"$set":
                {"friends.$.status" : 0}
    },

    function(err, result) {
        if (result) {
            console.log("SUCCESS");

        } else {
            console.log("FAIL");
        }
    });

我的查询运行正常但状态字段没有变化....请告诉我哪里错了?

1 个答案:

答案 0 :(得分:1)

查询工作正常,您可能会从正在使用的函数返回错误的值(emailfriend_req_sent_to)。

将所有status字段设置为1,运行:

db.test.update({
    email: "test3@gmail.com",
    friends: { $elemMatch: { friend_email: "test2@gmail.com" } }
}, { $set: { "friends.$.status": 0 } })

返回:

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

如果我查看find,我可以看到文档已正确更新。

相关问题