简体   繁体   English

如何使用聚合从 mongoDB 中对象的嵌套数组中提取信息

[英]How to use aggregation to pull information from a nested array on objects in mongoDB

I am trying to get the hang of the aggregation in mongoDB, I am new at this and I think I kinda got lost.我正在尝试掌握 mongoDB 中的聚合,我是新手,我想我有点迷路了。 I have a collection of users, each user has an array of social networks, and each item in this array is an object.我有一个用户集合,每个用户都有一个社交网络数组,这个数组中的每个项目都是一个对象。 How do I get value only from a given social network/s object/s.我如何仅从给定的社交网络/对象/对象中获取价值。

{
 "user":{
     "_id": "d10430c8-e59",
     "username": "John",
     "password": "f7wei93",
     "location": "UK",
     "gender": "Male",
     "age": 26,
     "socials": [
        {
            "type": "instagram",
            "maleFollowers": 23000,
            "femaleFollowers": 65000,
            "posts": 5400,
            "avgFollowerAge": 22
        },
        {
            "type": "facebook",
            "maleFollowers": 4000,
            "femaleFollowers": 6700,
            "posts": 330,
            "avgFollowerAge": 25
        },
        {
            "type": "snapchat",
            "maleFollowers": 873,
            "femaleFollowers": 1200,
            "posts": 1200,
            "avgFollowerAge": 21
        },

     ]
 }
}

I want to get the totalFollowersCount ( maleFollowers + femaleFollowers) for each social network type that is given in an array.我想获取数组中给出的每种社交网络类型的 totalFollowersCount(maleFollowers + femaleFollowers)。 for example ["instagram", "snapchat"] will only give me the totalFollowersCount for this two specific networks.例如 ["instagram", "snapchat"] 只会给我这两个特定网络的 totalFollowersCount。

I started playing around with aggregation but didn't figure it out all the way.我开始玩聚合,但一直没有弄明白。

First, we need to flatten the socials array.首先,我们需要展平socials数组。 Then, we group by socials type + 'user' fields and sum( maleFollowers + femaleFollowers) .然后,我们按社交type + 'user' 字段和sum( maleFollowers + femaleFollowers)

With $match operator, we filter desired social networks.使用$match运算符,我们过滤所需的社交网络。

db.users.aggregate([
  {
    $unwind: "$user.socials"
  },
  {
    $group: {
      _id: {
        user: "$user._id",
        type: "$user.socials.type"
      },
      "totalFollowersCount": {
        $sum: {
          $add: [
            "$user.socials.femaleFollowers",
            "$user.socials.maleFollowers"
          ]
        }
      }
    }
  },
  {
    $match: {
      "_id.type": {
        $in: [
          "instagram",
          "snapchat"
        ]
      }
    }
  }
])

MongoPlayground蒙戈游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM