1

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

2 Answers 2

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"}]}
);
answered Oct 29, 2019 at 17:42
Sign up to request clarification or add additional context in comments.

Comments

1

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' } })
answered Oct 29, 2019 at 17:40

2 Comments

Your answer did not work and gave error SyntaxError: missing } after property list @(shell):1:41
a , was deleted by mistake after inline editing :), added to answer

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.