0

I want to insert an element in an array by matching the sibling name. suppose-

{
    "_id": {
        "$oid": "60e544a5e0762b0b2ef6657e"
    },
    "user0": "a",
    "details": [{
        "name": "jon",
        "things": [{
            "name": "car",
            "work": "travel"
        }, {
            "name": "phone",
            "work": "network"
        }]
     },{
        "name": "steve",
        "things": [{
            "what": "car",
            "work": "travel"
        }, {
            "what": "phone",
            "work": "network"
        }]
    }]
}

I want to insert an object in "things" array with where name is "steve" right now I am doing it like this but is doesn't work

collection.updateOne({_id:docs[0]._id}, {$push:{"details.$[]":{things:req.body.data}}});
Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43
armdthm
  • 9
  • 2
  • 1
    Does this answer your question? [How to insert an element to MongoDB internal list?](https://stackoverflow.com/questions/13987365/how-to-insert-an-element-to-mongodb-internal-list) – turivishal Jul 07 '21 at 07:46

1 Answers1

0

You want to be using arrayFilters, it gives you the ability to update a specific element in an array with a query, in this case the element that has the name "steve":

db.collection.update(
{
   _id:docs[0]._id
},
{
  $push: {
    "details.$[elem].things": req.body.data
  }
},
{
  arrayFilters: [
    {
      "elem.name": "steve"
    }
  ]
})

Mongo Playground

Tom Slabbaert
  • 21,288
  • 10
  • 30
  • 43
  • You can answer in [duplicate question](https://stackoverflow.com/questions/13987365/how-to-insert-an-element-to-mongodb-internal-list) if your solution is not available there. and you can close this question by duplicate vote. – turivishal Jul 07 '21 at 08:46