我有以下结构:

{
   "_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
      }
   ]
}


我想$addFields is_liked如果likedBy数组包含user_id$projectlikedBy: 0隐藏该数组

 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", [] ] } ] }

        }
      }
    }
  }
}  ])


问题是在每个项目中都重复了$map数组:屏幕截图:https://prnt.sc/lzrwln

基本上,最终结果是将likedBy数组替换为is_liked: true/false,因此我不必将数组携带在FE中只是为了检查用户是否喜欢

最佳答案

您可以使用$mergeObjects将现有的tweet与is_liked字段组合在一起,然后使用$project从最终结果中排除likedBy数组,请尝试:

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

10-01 03:33