更新MongoDB中精确元素数组中的字段

时间:2012-05-03 13:43:29

标签: mongodb mongodb-query nosql

我的文档结构如下:

{
    _id:"43434",
    heroes : [
        { nickname : "test",  items : ["", "", ""] },
        { nickname : "test2", items : ["", "", ""] },
    ]
}

我可以$set使用items heros nickname数组"test"中嵌入对象的{ _id:"43434", heroes : [ { nickname : "test", items : ["", "new_value", ""] }, // modified here { nickname : "test2", items : ["", "", ""] }, ] } 数组的第二个元素吗?

结果:

{{1}}

4 个答案:

答案 0 :(得分:124)

您需要使用2个概念:mongodb's positional operator并只使用要更新的条目的数字索引。

位置运算符允许您使用如下条件:

{"heros.nickname": "test"}

然后像这样引用找到的数组条目:

{"heros.$  // <- the dollar represents the first matching array key index

如果你想更新“items”中的第二个数组条目,并且数组键被索引为0 - 那就是键1。

所以:

> db.denis.insert({_id:"43434", heros : [{ nickname : "test",  items : ["", "", ""] }, { nickname : "test2", items : ["", "", ""] }]});
> db.denis.update(
    {"heros.nickname": "test"}, 
    {$set: {
        "heros.$.items.1": "new_value"
    }}
)
> db.denis.find()
{
    "_id" : "43434", 
    "heros" : [
        {"nickname" : "test", "items" : ["", "new_value", "" ]},
        {"nickname" : "test2", "items" : ["", "", "" ]}
    ]
}

答案 1 :(得分:0)

db.collection.update(
{
heroes:{$elemMatch:{ "nickname" : "test"}}},
 {
     $push: {
        'heroes.$.items': {
           $each: ["new_value" ],
           $position: 1
        }
     }
   }

)

答案 2 :(得分:0)

此解决方案效果很好。只想增加一点。 这是结构。我需要找到OrderItemId为'yyy'并进行更新。 如果条件中的查询字段为数组,则如下所示,“ OrderItems.OrderItemId”为数组。您不能将“ OrderItems.OrderItemId [0]”用作查询中的操作。相反,您需要使用“ OrderItems.OrderItemId”进行比较。否则,它不能匹配一个。

{
  _id: 'orderid',
  OrderItems: [
   {
     OrderItemId: ['xxxx'], 
    ... },
   {
     OrderItemId: ['yyyy'], 
    ...}, 
]

}
 result =  await collection.updateOne(
        { _id: orderId, "OrderItems.OrderItemId": [orderItemId] },
        { $set: { "OrderItems.$.imgUrl": imgUrl[0], "OrderItems.$.category": category } },
        { upsert: false },
      )
    console.log('  (result.modifiedCount) ', result.modifiedCount)
    console.log('  (result.matchedCount) ', result.matchedCount)

答案 3 :(得分:0)

试试update document in array using positional $

位置 $ 运算符有助于更新包含嵌入文档的数组。使用位置 $ 运算符访问带有 $ 运算符上的点符号的嵌入文档中的字段。

db.collection.update(
  { "heroes.nickname": "test" },
  { $set: { "heroes.$.items.1": "new_value" } },
  { multi: true }
);

Playground