MongoDB -更新数组中特定元素方法

0x6upsns  于 2022-11-22  发布在  Go
关注(0)|答案(1)|浏览(225)

更新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" } ],
}
ql3eal8s

ql3eal8s1#

1.应该是placename,但不是name。否则它将不会筛选任何要更新的文档。
1.当前的$set将覆盖对象的frnds数组。您需要将$[<identifier>]位置筛选运算符与arrayFilters一起使用。

db.collection.update({
  "placename": "khulna",
  "frnds.name": "osama"
},
{
  $set: {
    "frnds.$[f]": {
      name: "rasana",
      cost: "212871"
    }
  }
},
{
  arrayFilters: [
    {
      "f.name": "osama"
    }
  ]
})

Demo @ Mongo Playground

const query = {
  "placename": "khulna",
  "frnds.name": "osama"
};
const updateDocument = {
  $set: {
    "frnds.$[f]": {
      name: "rasana",
      cost: "212871"
    }
  }
};
const result = await db.collection(<collection_name>).updateOne(query, updateDocument, {
  arrayFilters: [
    {
      "f.name": "osama"
    }
  ]
});

相关问题