12

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 3

26

Two possibilities here:

  1. Since you don't have an unique identifier for the comments, the only way to update an specific item on the comments array is to explicitly indicate the index you are updating, like this:

    db.documents.update(
      { _id: "iL9hL2hLauoSimtkM"},
      { $push: { "comments.0.likes": "userID3" }}
    );
    
  2. If you add an unique identifier for the comments, you can search it and update the matched item, without worrying with the index:

    db.documents.update(
      { _id: "iL9hL2hLauoSimtkM", "comments._id": "id1"},
      { $push: { "comments.$.likes": "userID3" }}
    );
    
Sign up to request clarification or add additional context in comments.

1 Comment

just wonder if it were possible to update multiple array items with one update? I have a case where it can be up to 50 updates per document.
2

You can try $addToSet which adds elements to an array only if they do not already exist in the set.

db.topics.update(
   { _id: "iL9hL2hLauoSimtkM" },
   { $addToSet: {  "comments.0.likes": "userId3" } }
)

1 Comment

Finally an answer that actually works
0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.