My data structure looks like this:
{
"_id" : .....,
"topicId" : topicId1,
"category": .....,
"other things"....,
"posts": [
{postId:id1,
username:.....,
postBody: 'some text here'
},
{postId:id2,
username:.....,
postBody: ' some other text here'
}
]
}
My goal is to find a document where topicId equal to some Id, after that in the document find in posts an object where its postId equal to some Id, and finally update postBody in that object.
At the end it should look like this:
{
"_id" : .....,
"topicId" : topicId1,
"category": .....,
"other things"....,
"posts": [
{postId:id1,
username:.....,
postBody: 'some text here'
},
{postId:id2,
username:.....,
postBody: 'HERE IS UPDATED TEXT'
}
]
}
This is how i'm deleting a post:
db.collection('topics').findOneAndUpdate({ 'topicId': topicId }, { $pull: { 'posts': { 'postId': postId } } })
But i have no idea how to update it based on my data structure. I'd appreciate any help.
asked Oct 29, 2019 at 17:09
Noob
2,8454 gold badges25 silver badges46 bronze badges
2 Answers 2
You can try this:
01) Example of Document:
{
"topicId" : "5db85e379a17899b8ba631ca",
"category": "category",
"other things": "Other Things",
"posts": [
{
postId: "5dae22702486f7d89ba7633c",
username: "TheUserName",
postBody: 'Some Text Here'
},
{
postId: "5db85e439a17899b8ba631cd",
username: 'TheOtherUserName',
postBody: 'Some Other Text Here'
}
]
}
02) Query:
db.collection('topics').update(
{"topicId" : "5db85e379a17899b8ba631ca"},
{ $set: { "posts.$[outer].postBody" : "HERE IS UPDATED TEXT" } },
{ multi: true, arrayFilters: [{"outer.postId" : "5db85e439a17899b8ba631cd"}]}
);
Sign up to request clarification or add additional context in comments.
Comments
considering your data is
{
"topicId" : "topicId1",
"posts": [
{"postId":"id1",
"postBody": "some text here"
},
{"postId":"id2",
"postBody": "some other text here"
}
]
}
you can use simple updateOne by filter and then $set
db.blah.updateOne({ topicId: 'topicId1', 'posts.postId': 'id2' }, { $set: { 'posts.$.postBody': 'HERE IS UPDATED TEXT' } })
2 Comments
barrypicker
Your answer did not work and gave error
SyntaxError: missing } after property list @(shell):1:41Robot
a , was deleted by mistake after inline editing :), added to answer
lang-js