使用updateMany()和MongoDB

时间:2018-03-16 16:43:11

标签: javascript arrays node.js mongodb

在我的MongoDB / Node后端,我正在尝试编写一个接收用户输入ID的函数,然后更新一个名为subscription.subscriptionEnd的字段,该字段匹配每个传入ID的字段。

我正在更新的值对于所有输入的记录都是相同的。我的挑战是在一个名为“subscription”(它位于文档的根目录)的数组中定位正确的元素。我想要做的只是为每个与输入ID之一匹配的数组元素更新subcriptionEnd属性。

我的数据如下:

{
        "_id": "1234",
        "name": {
            "first": "John",
            "last": "Smith"
        },
        "branch": "New York",
        "dob": null,
        "subscription": [
            {
                "field1": null,
                "field2": null,
                "subscriptionEnd": "2015-05-31T00:00:00.000Z",
                "_id": "7777"
            },
            {
                "field1": null,
                "field2": null,
                "subscriptionEnd": "2015-05-31T00:00:00.000Z",
                "_id": "9999"
            }
        ]
}

因此,想象一下我只想为“_id”为“7777”的数组元素更新“subscriptionEnd”属性值,而不是为“_id”为“9999”的数组元素更新。

如何正确制作这些地图?一位评论者昨天动态地提到了映射,做了类似的事情:

db.collection('clients').updateMany( 
 { _id: { $in: mongoArrRecords }, "subscription.someOtherProp":value},
 { $set: { "subscription.$.subscriptionEnd": lastDayOfMonth } }
)

但我不清楚在这种情况下映射到什么。有没有办法可以确保这个映射正确 - 只针对包含其中一个输入ID的相同数组元素?

当然,如果我知道有问题的数组元素,我可以直接定位,如下所示:

db.collection('clients').updateMany( 
 { _id: { $in: mongoArrRecords } },
 { $set: { "subscription.0.subscriptionEnd": lastDayOfMonth } }
)

但我不知道这一点。

知道的是,它是相同的数组元素,其中_id作为数组的一部分通过$in运算符传递到。

1 个答案:

答案 0 :(得分:1)

您需要使用两个数组属性。要查询的一个数组属性和要更新的另一个数组属性。

尝试

db.collection('clients').updateMany( 
   { "subscription._id":{ $in: mongoArrRecords }}, 
   { $set: { "subscription.$.subscriptionEnd": lastDayOfMonth } } 
) 

只要您针对一个数组定位一个目标,就应该有效。

您可以使用[<identifier>]扩展上述方法,以使用3.6中的arrayFilters概念定位单个文档中的多个数组元素。

db.collection('clients').updateMany(
   { },
   { $set: { "subscription.$[subr].subscriptionEnd" : lastDayOfMonth  } },
   {
     arrayFilters: [{ "subr._id":{ $in: mongoArrRecords }} ]
   }
)