【问题标题】:Mapping To Correct Array When Using updateMany() and MongoDB使用 updateMany() 和 MongoDB 时映射到正确的数组
【发布时间】:2018-03-16 16:43:10
【问题描述】:

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

我更新到的值对于所有输入的记录都是相同的。我的挑战是在一个名为“订阅”(位于文档的根目录)的数组中定位正确的元素。我想要做的只是更新与输入 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”的数组元素更新“subscriptionEnd”属性值.

如何正确制作这些地图?一位评论者昨天提到动态映射,通过这样做:

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 } }
)

但我不知道这个。

知道的是,通过$in 运算符作为数组的一部分传入的_id 与映射到的数组元素相同。

【问题讨论】:

  • 是的,它将针对正确的元素。尝试db.collection('clients').updateMany( { _id: { $in: mongoArrRecords }, "subscription._id":"7777"}, { $set: { "subscription.$.subscriptionEnd": lastDayOfMonth } } ) 处理您的情况。
  • 对,但要澄清一下,我不知道值。所以我不能硬编码“7777”。它需要根据来自 $in: mongoArrRecords 的 ID 动态映射。
  • 我认为你也可以这样做。你能给我们看看 mongoArrRecords 的样本吗?
  • 这可能会有所不同,因为它是一个由用户传入的数组。所以它可能是 [7777, 4444, 3333, 5656, 2345, 6574] 等。我在这里使用的是编造的数字,请记住它是一个 mongo 对象 ID 的数组。
  • 这个问题和stackoverflow.com/questions/49309816/…有什么不同?

标签: javascript arrays node.js mongodb


【解决方案1】:

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

试试

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

只要您为一个数组定位一个 objectid,这应该可以工作。

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

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

【讨论】:

    猜你喜欢
    • 2014-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-29
    • 1970-01-01
    • 2021-12-23
    • 2023-01-01
    • 1970-01-01
    相关资源
    最近更新 更多