Noob
Noob

Reputation: 2807

How do I update a value not only in all documents but also in array of documents that a document can have?

I have a collection of topics with data that looks like this:

{
  topicId:"LSCv0mnb" ,
  createdBy:"Sam",
  posts:[
   {
    postId: "nNP8UDxL",
    createdBy: "Sam"
   }, 
   {
    postId: "aJ8UxLa",
    createdBy: "Bob"
   }
 ]
}

{
  topicId:"hlsTOgAX" ,
  createdBy:"Victoria",
  posts:[
   {
    postId: "E3cJa0Nm",
    createdBy: "Sam"
   }, 
   {
    postId: "Rt0xQnAy",
    createdBy: "Jessica"
   }
 ]
}

What I need is to be able to find all createdBy where name is Sam in all documents and in the array of posts and replace it with [deleted] for example:

{
  topicId:"LSCv0mnb" ,
  createdBy:"[deleted]",
  posts:[
   {
    postId: "nNP8UDxL",
    createdBy: "[deleted]"
   }, 
   {
    postId: "aJ8UxLa",
    createdBy: "Bob"
   }
 ]
}

I'm kind of lost how to do it correctly. Should I be using aggregations for it or what would be the way to do it ? Thanks for your help.

Upvotes: 1

Views: 17

Answers (1)

turivishal
turivishal

Reputation: 36134

  • $match createdBy condition
  • $map to iterate loop of posts array, check condition if createdBy is "Sam" then replace string otherwise nothiing
db.collection.aggregate([
  { $match: { createdBy: "Sam" } },
  {
    $addFields: {
      createdBy: "[deleted]",
      posts: {
        $map: {
          input: "$posts",
          in: {
            postId: "$$this.postId",
            createdBy: {
              $cond: [
                { $eq: ["$$this.createdBy", "Sam"] },
                "[deleted]",
                "$$this.createdBy"
              ]
            }
          }
        }
      }
    }
  }
])

Playground

Upvotes: 1

Related Questions