繁体   English   中英

如何更新MongoDB中数组中的特定数据?

[英]How to update specific data in array in MongoDB?

{
  "_id":{"$oid":"5f5287db8c4dbe22383eca58"},
  "__v":0,
  "createdAt":{"$date":"2020-09-12T11:35:45.965Z"},
  "data":["Buy RAM","Money buys freedom"],
  "updatedAt":{"$date":"2020-09-12T11:38:10.637Z"}
}

我想将此数据数组字段中的第一个元素更新为Buy SSD

我如何使用 NodeJS 做到这一点?

db.collection.findOneAndUpdate({
    "_id.$oid": "5f5287db8c4dbe22383eca58",
    data: "Buy RAM"
}, {
    $set: {
        "data.$" "Buy SSD"
    }
})

此查询使用$位置标识符更新文档内data数组中与"_id.$oid": "5f5287db8c4dbe22383eca58"匹配的第一个元素,并将其设置为新值。

有关mongodb更多Array Update Operators ,请参考: mongodb 手册

您可以使用过滤的位置运算符

db.collectionName.updateOne(
{
    "_id.$oid": "5f5287db8c4dbe22383eca58"
}, 
{
    $set: {
        "data.$[element]": "Buy SSD"
    }
},
{
    { arrayFilters: [ { element: "Buy Ram" } ] }
})

注意:它将更新与文本匹配的所有数组元素。 在这种情况下,“购买 Ram”

您可以使用str.replace()

var product = 
    [{
      "_id":{"$oid":"5f5287db8c4dbe22383eca58"},
      "__v":"0",
      "createdAt":{"$date":"2020-09-12T11:35:45.965Z"},
      "data":["Buy RAM","Money buys freedom"],
      "updatedAt":{"$date":"2020-09-12T11:38:10.637Z"}
    }]
var new_product = JSON.stringify(product).replace("Buy RAM", "Something");
console.log(new_product);

UpdateOne -> 更新单个Document

db.collection.updateOne(filter, update, options)

您可能会使用_id字段进行过滤,并使用$set更新特定字段

使用点符号来访问和设置对象内部深处的字段,而不影响这些对象的其他属性。

您想更新“数据”中的第一个数组条目,并且数组键的索引为 0 - 这就是键0

所以查询看起来像这样:

    db.collection.update(
       { _id: { "$oid": "56476e04e5f19d86ece5b81d"}, // probb ObjectId Instance
       { $set:
          {
            "data.0": "Buy SSD" // Using dot-notation
          }
       }
    )

对于更高级的使用,您可以使用MongoDB 的位置运算符$而无需显式指定元素在数组中的位置。 位置运算符允许您使用这样的条件:

{"Order.name": "test"}

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

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

例子:

/* DATA
{
    "_id" : "43434", 
    "Order" : [
        {"name" : "test", "items" : ["", "new_value", "" ]},
        {"name" : "test2", "items" : ["", "", "" ]}
    ]
}
 */ 

db.collection.update(
   { _id: "43434", "Order.name": "test2"},
   { $set:
      {
        "Order.$.items.1": "new_value2" // positional operator & dot-notation.
      }
   }
)
>>> db.collection.find()  
{
    "_id" : "43434", 
    "Order" : [
        {"name" : "test", "items" : ["", "new_value", "" ]},
        {"name" : "test2", "items" : ["", "new_value2", "" ]}
    ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM