Insert element into nested arrays in MongoDB

Viewed 14906

I am new to mongoDB. I am having some trouble in updating the records in mongoDB collection.

How to add elements into array likes into the embedded record

I have a embedded collection like:

{
  "_id": "iL9hL2hLauoSimtkM",
  "title": "Some Topic",
  "followers": [
    "userID1",
    "userID2",
    "userID3"
  ],
  "comments": [
    {
      "comment": "Yes Should be....",
      "userId": "a3123",
      "likes": [
        "userID1",
        "userID2"
      ]
    },
    {
      "comment": "No Should not be....",
      "userId": "ahh21",
      "likes": [
        "userID1",
        "userID2",
        "userID3"
      ]
    }
  ]
}

I want to update the record as

{
  "_id": "iL9hL2hLauoSimtkM",
  "title": "Some Topic",
  "followers": [
    "userID1",
    "userID2",
    "userID3"
  ],
  "comments": [
    {
      "comment": "Yes Should be....",
      "userId": "a3123",
      "likes": [
        "userID1",
        "userID2",
        "userID3" // How to write query to add this element.
      ]
    },
    {
      "comment": "No Should not be....",
      "userId": "ahh21",
      "likes": [
        "userID1",
        "userID2",
        "userID3"
      ]
    }
  ]
}

Please provide the query to add the element shown in comment. Thank you.

3 Answers

Try this:

db.<collection>.updateOne(
   {_id:"iL9hL2hLauoSimtkM",comments:{$elemMatch:{userId:'a3123'}}},
   {$push:{'comments.$.likes':'userID3'}})

$ operator is equivalent to the filter

$ === {_id:"iL9hL2hLauoSimtkM",comments:{$elemMatch:{userId:'a3123'}}}

nevertheless, we are basically pushing "userID3" into

[1] the "likes" array
[2] inside the specified element === $
[3] which belonging to the "comments" array

Related