Home > database >  Replace items into mongo object via mongoose
Replace items into mongo object via mongoose

Time:01-28

I want to edit an item in my mongodb collection.

In my database, I have a "person" that has the following value:

{
"_id": {Random Object Id},
"property": [{
  "model": ["BMW", "Toyota", "Honda"],
  "color": ["red", "blue", "yellow"],
}, {
  "model": ["Test0", "Test1", "Test2"],
  "color": ["black", "blue", "brown"],
}]
}

Here the "property" is an Array and has 2 objects. Also all of them should be in order. I want to change one of the value in the second object. The second object should be like

  "model": ["Test0", "Test1", "Test2"],
  "color": ["black", "red", "brown"],

How do I apply this kind of code in my express server and also how do I place the "red" color into the second element ?

personModel.findByIdAndUpdate({_id: req.session.person._id}, {$set: {
`property.$[index].color` : "red"}})

CodePudding user response:

If you know the index you can just manually define it:

db.collection.updateOne(
{_id: req.session.person._id},
{
  "$set": {
    "property.1.color.1": "red"
  }
})

Mongo Playground

If you want to change a specific color you should use the update arrayFilters option, like so:

db.collection.updateOne(
{_id: req.session.person._id},
{
  "$set": {
    "property.1.color.$[elem]": "red"
  }
},
{
  arrayFilters: [
    {
      elem: "blue"
    }
  ]
})

Mongo Playground

  •  Tags:  
  • Related