Noob
Noob

Reputation: 2807

MongoDB - How to update an object in an array?

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.

Upvotes: 1

Views: 80

Answers (2)

Robot
Robot

Reputation: 991

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

Upvotes: 1

Haruo
Haruo

Reputation: 516

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

Upvotes: 2

Related Questions