0

how to update certain object using its's id in the posts array for example changing the the first object in posts using it's id

{
"_id" : ObjectId("5e3929127b0a7599f0a33b90"),
"posts" : [ 
    {
        "title" : "title",
        "desc" : "body",
        "id" : ObjectId("5e396faeac120790c4561f4b")
    },
      {
        "title" : "title2",
        "desc" : "body2",
        "id" : ObjectId("5e396faeac120790c4561x2t")
    }
],
"name" : "jarvis",
"email" : "jarvis@yahoo.com",
"password" : "123",
"__v" : 0

}

to be something like this

 {
"_id" : ObjectId("5e3929127b0a7599f0a33b90"),
"posts" : [ 
    {
        "title" : "new title",
        "desc" : "new body",
        "id" : ObjectId("5e396faeac120790c4561f4b")
    },
      {
        "title" : "title2",
        "desc" : "body2",
        "id" : ObjectId("5e396faeac120790c4561x2t")
    }
],
"name" : "jarvis",
"email" : "jarvis@yahoo.com",
"password" : "123",
"__v" : 0

}

  • You question is a duplicate of https://stackoverflow.com/questions/11372065/mongodb-how-do-i-update-a-single-subelement-in-an-array-referenced-by-the-inde – Azzy Feb 04 '20 at 14:05
  • 1
    Welcome, similar questions have been answered before eg. [link](https://stackoverflow.com/questions/9401668/updating-a-sub-document-in-mongodb). You can also find more about handling nested documents in MongoDB's [documentation](https://docs.mongodb.com/manual/tutorial/query-embedded-documents/). – Penguin74 Feb 04 '20 at 14:05
  • Di you want to update always the **first** element in `post[]` or the post having `id = ObjectId("5e396faeac120790c4561f4b")` – Wernfried Domscheit Feb 04 '20 at 14:25

2 Answers2

1

Would be this one with arrayFilters

db.col.updateMany(
   {},
   {
      $set: {
         "posts.$[p].title": "new title",
         "posts.$[p].desc": "new body"
      }
   },
   { arrayFilters: [{ "p.id": ObjectId("5e396faeac120790c4561f4b") }] }
)

arrayFilters have been introduced in MongoDB version 3.6

Wernfried Domscheit
  • 54,457
  • 9
  • 76
  • 110
0

Do you mean this?

yourModel.updateOne({
    "posts.id": ObjectId("5e396faeac120790c4561f4b")
}, {
    $set: {
        "posts.0.title": "new title",
        "posts.0.desc": "new body"
    }
}).then(console.log).catch(console.log);
Hlib Derbenov
  • 916
  • 1
  • 7
  • 15
  • 1
    How do you know that you always have to update element 0? The post could be at any position in array `posts[]`. – Wernfried Domscheit Feb 04 '20 at 14:16
  • @WernfriedDomscheit "for example changing the first object in posts using it's id". That's not the universal solution, I agree. To update а specific element we need to use positional operator $. – Hlib Derbenov Feb 04 '20 at 14:21