MongoDB更新对象的嵌套对象值

时间:2018-05-28 16:24:45

标签: node.js mongodb

我的格式为:

{
        "_id" : ObjectId("5af44cfbe2e96c58ec402efb"),
        "username" : "egealpay2",
        "email" : "egealpay2@gmail.com",
        "fullName" : "ege",
        "pnumber" : "",
        "oneSignal" : "d427dcdf-7939-4ada-a035-be74e1e45091",
        "friends" : [
                {
                        "email" : "baransrc@gmail.com",
                        "status" : 2
                }
        ],
        "alarms" : [
                {
                        "id" : "2",
                        "title" : "before",
                        "location" : "default",
                        "startTime" : "2018-05-16\t\t\t16:29",
                        "endTime" : "16:29\t\t\t17 - 05 - 2018",
                        "remindAt" : "17:29\t\t\t15 - 05 - 2018",
                        "privacy" : "0",
                        "userORJoinedAlarm" : "1",
                        "eventJoiners" : [
                                {
                                        "email" : "ilkersadya@sabanciuniv.edu",
                                        "status" : 1
                                },
                                {
                                        "email" : "ilkercankayasss@sabanciuniv.edu",
                                        "status" : 1
                                },
                                {
                                        "email" : "ilkearcankaya@sabanciuniv.edu",
                                        "status" : 1
                                },
                                {
                                        "email" : "iaaalkercankaya@sabanciuniv.edu",
                                        "status" : 1
                                }
                        ],
                        "comments" : [ ]
                }
        ]
}

我想设置status: 2的{​​{1}}"闹钟:" ," eventJoiners" :"email" : "ilkersadya@sabanciuniv.edu", its under" ID"`

我尝试使用push with $但是无法设法让它工作并且它已经让我烦恼了2个多小时。

更新我曾试过感谢@Ashish:

which has an id of 2 as

得到了错误

 dbo.collection("users").findOne( { email: userId } , function(errZer, addedZer) {
          dbo.collection("users").findOneAndUpdate( {email: addedID, "alarms.id": eventIDGiv,  alarms: { $elemMatch: { id: '2', eventJoiners: { $elemMatch: { email: addedID } } }} },
          { $set: { "alarms.$.eventJoiners.$.status": '2' } , function(err, added) {

1 个答案:

答案 0 :(得分:1)

位置运算符($)只能用于一级嵌套数组。在您的情况下,您必须为alarmseventJoiners指定条件。为此,您可以使用$[< identifier >]语法(可在MongoDB 3.6 +中使用):

db.collection.update(
    { _id: ObjectId("5af44cfbe2e96c58ec402efb") },
    { $set: { "alarms.$[elem1].eventJoiners.$[elem2].status": "2" } },
    { arrayFilters: [ { "elem1.id": "2" }, { "elem2.email": "ilkersadya@sabanciuniv.edu" } ]})

在这种情况下,标识符elem1elem2用作arrayFilters部分中指定条件的占位符。