Home > Enterprise >  MongoDB - Way of update a specific element in array
MongoDB - Way of update a specific element in array

Time:11-16

To update a specific element in the array on MongoDB collection.

MongoDB data -

{
  _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" } ],
}

I want to update frnds arrays with the specific element that matches by name. I try this way but it's not working.

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);

After the update, the document like -

{
  _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" } ],
}

CodePudding user response:

  1. Should be placename but not name. Otherwise it will not filter any document to be update.

  2. The current $set will override the frnds array to object. You need to use $[<identifier>] positional filtered operator with 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"
    }
  ]
});
  • Related