1

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.

1 Answer 1

1
  • $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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.