Insert element into nested arrays in MongoDB

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" } }
)

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" }}
    );
    

Tags:

Mongodb

Meteor