Denko Mancheski
Denko Mancheski

Reputation: 2719

MongoDB $addFields and $in in aggregate

I have the following structure:

{  
   "_id":"some_id",
   "tweets":[  
      {  
         "id":"1077633161922785281",
         "created_at":"Tue Dec 25 18:32:21 +0000 2018",
         "favorite_count":1905,
         "retweet_count":27,
         "media":[  

         ],
         "text":"Chillin",
         "avatar":"https://pbs.twimg.com/profile_images/1062579676508381184/gDukIs20_normal.jpg",
         "name":"Chance Morris",
         "display_name":null,
         "user_id":"1087348778",
         "likedBy":[  
            "some-random-dude"
         ],
         "likes":1
      }
   ]
}

I would like to $addFields is_liked if likedBy array contains user_id and $project :likedBy: 0 to hide the array

 db().collection('gamers').aggregate([
{
  $project: {
    'tweets.likedBy': 0
  }
},
{
  $addFields: {
    'tweets.is_liked': {
      $map: {
        input: "$tweets",
        as: "tweet",
        in: {
          id: "$$tweet.id",
          text: "$$tweet.text",
          is_liked: { $in: [ "some-random-dude", { $ifNull: [ "$$tweet.likedBy", [] ] } ] }

        }
      }
    }
  }
}  ])

The issue is that the $map array is repeated in every item: screenshot: https://prnt.sc/lzrwln

Basically the end result would be replacing the likedBy array with is_liked: true/false, so I will not have to carry the array in FE just to check if the user liked or not

Upvotes: 1

Views: 540

Answers (1)

mickl
mickl

Reputation: 49945

You can use $mergeObjects to combine existing tweet with is_liked field and then use $project to exclude likedBy array from final result, try:

db.gamers.aggregate([
    {
        $project: {
            tweets: {
                $map: {
                    input: "$tweets",
                    as: "tweet",
                    in: {
                        $mergeObjects: [
                            "$$tweet",
                            { is_liked: { $in: [ "some-random-dude", { $ifNull: [ "$$tweet.likedBy", [] ] } ] } }
                        ]                            
                    }
                }
            }
        } 
    },
    {
        $project: {
            "tweets.likedBy": 0
        }
    }
])

Upvotes: 2

Related Questions