MongoDB $ addFields和$ in总计 [英] MongoDB $addFields and $in in aggregate

查看:218
本文介绍了MongoDB $ addFields和$ in总计的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下结构:

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

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

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

        }
      }
    }
  }
}  ])

问题在于,在每个项目中都重复了$map数组:屏幕快照: https://prnt.sc/lzrwln

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

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

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

推荐答案

您可以使用 $ mergeObjects 将现有的tweet与is_liked字段合并,然后使用

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

这篇关于MongoDB $ addFields和$ in总计的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆