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.
If the value is an array, $push appends the whole array as a single element. To add each element of the value separately, use the $each modifier with $push . For an example, see Append a Value to Arrays in Multiple Documents. For a list of modifiers available for $push , see Modifiers.
Update Nested Arrays in Conjunction with $[] The $[<identifier>] filtered positional operator, in conjunction with the $[] all positional operator, can be used to update nested arrays. The following updates the values that are greater than or equal to 8 in the nested grades. questions array if the associated grades.
ArrayList<String> stringArray = new ArrayList<String>(); BasicDBObject document = new BasicDBObject(); document. put("master", stringArray); db. getCollection("master"). insert(document);
In MongoDB, you can only nest document up to 100 levels. The overall document size must not exceed 16 MB.
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" }}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With