更新MongoDB集合上数组中的特定元素。
MongoDB数据-
{
_id: new ObjectId("63608e3c3b74ed27b5bdf703"),
placename: "khulna",
frnds: [
{ name: "osama", cost: "2121" },
{ name: "lotid", cost: "2121" },
{ name: "haris", cost: "2121" },
{ name: "atiq", cost: "2121" } ],
},
{
_id: new ObjectId("63608e3c3b74ed27b5bdf703"),
plmarshal: "narishal",
frnds: [
{ name: "ojda", cost: "2121" },
{ name: "majid", cost: "2121" },
{ name: "nafis", cost: "2121" },
{ name: "rofiq", cost: "2121" } ],
},
{
_id: new ObjectId("63608e3c3b74ed27b5bdf703"),
placename: "latin america",
frnds: [
{ name: "mamun", cost: "2121" },
{ name: "lotifa", cost: "2121" },
{ name: "sajid", cost: "2121" },
{ name: "natiq", cost: "2121" } ],
}
我想用名称匹配的特定元素更新frnds
数组。我尝试了这种方法,但没有效果。
const query = { name: "khulna", "frnds.name": "osama"};
const updateDocument = { $set: {frnds: { name: "rasana", cost: "212871" } } };
const result = await db.collection(<collection_name>).updateOne(query, updateDocument);
更新后,文档如-
{
_id: new ObjectId("63608e3c3b74ed27b5bdf703"),
placename: "khulna",
frnds: [
{ name: "rasana", cost: "212871" }, //// previus { name: "osama", cost: "2121" }
{ name: "lotid", cost: "2121" },
{ name: "haris", cost: "2121" },
{ name: "atiq", cost: "2121" } ],
}
1条答案
按热度按时间ql3eal8s1#
1.应该是
placename
,但不是name
。否则它将不会筛选任何要更新的文档。1.当前的
$set
将覆盖对象的frnds
数组。您需要将$[<identifier>]
位置筛选运算符与arrayFilters
一起使用。Demo @ Mongo Playground