Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
MongoDB中精确元素数组中的更新字段_Mongodb_Mongodb Query_Nosql - Fatal编程技术网

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

MongoDB中精确元素数组中的更新字段,mongodb,mongodb-query,nosql,Mongodb,Mongodb Query,Nosql,我的文档结构如下: { _id:"43434", heroes : [ { nickname : "test", items : ["", "", ""] }, { nickname : "test2", items : ["", "", ""] }, ] } {"heroes.nickname": "test"} 我可以$set数组heros中嵌入对象的项数组的第二个元素,并使用昵称

我的文档结构如下:

{
    _id:"43434",
    heroes : [
        { nickname : "test",  items : ["", "", ""] },
        { nickname : "test2", items : ["", "", ""] },
    ]
}
{"heroes.nickname": "test"}
我可以
$set
数组
heros
中嵌入对象的
数组的第二个元素,并使用
昵称

结果:

{
    _id:"43434",
    heroes : [
        { nickname : "test",  items : ["", "new_value", ""] }, // modified here
        { nickname : "test2", items : ["", "", ""] },
    ]
}

您需要使用两个概念:简单地使用数字索引来更新条目

“位置”操作符允许您使用如下条件:

{
    _id:"43434",
    heroes : [
        { nickname : "test",  items : ["", "", ""] },
        { nickname : "test2", items : ["", "", ""] },
    ]
}
{"heroes.nickname": "test"}
然后引用找到的数组项,如下所示:

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

尝试使用位置$和更新


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

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

}
试试看

位置$operator有助于更新包含嵌入文档的数组。使用位置$operator访问嵌入文档中的字段,并在$operator上使用点表示法

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

如何访问匹配元素的值?比如{“heros.$.items.2”:“heros.$.nickname”}@ad7six如何更新最后一个元素。我不知道数组的大小。(在python中类似于items[-1]=“new value”)。@Amit如果需要:by=)
db.collection.update(
  { "heroes.nickname": "test" },
  { $set: { "heroes.$.items.1": "new_value" } },
  { multi: true }
);