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.
Two possibilities here:
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" }}
);
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" }}
);