Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/mongodb/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mongodb 复杂对象上的聚合_Mongodb_Mongodb Query - Fatal编程技术网

Mongodb 复杂对象上的聚合

Mongodb 复杂对象上的聚合,mongodb,mongodb-query,Mongodb,Mongodb Query,我收集了以下文件: { "towers": [ { "name": "foo", "towers": [ { "name": "A", "buildType": "Apartament" }, { "name": "B", "buildType": "Apartament" } ] }, {

我收集了以下文件:

{
  "towers": [
    {
      "name": "foo",
      "towers": [
        {
          "name": "A",
          "buildType": "Apartament"
        },
        {
          "name": "B",
          "buildType": "Apartament"
        }
      ]
    },
    {
      "name": "xpto",
      "towers": [
        {
          "name": "C",
          "buildType": "House"
        },
        {
          "name": "D",
          "buildType": "Office"
        }
      ]
    }
  ]
}
我只需要知道“buildType”的所有可能值,比如:

  • 公寓
  • 房子
  • 办公室
这是一个复杂的对象,要聚合的数据就在其中。有什么方法可以实现我想要的结果吗?

您需要创建两个嵌套数组,即“towers”和“towers.towers”,然后与“towers.towers.buildType”字段一起使用以获得不同的值

db.collection.aggregate([
  { "$unwind": "$towers" },
  { "$unwind": "$towers.towers" },
  { "$group": {
    "_id": "$towers.towers.buildType"
  }}
])
输出

[
  {
    "_id": "Office"
  },
  {
    "_id": "House"
  },
  {
    "_id": "Apartament"
  }
]
db.collection.aggregate(

    // Pipeline
    [
        // Stage 1
        {
            $unwind: {
                path: "$towers",

            }
        },

        // Stage 2
        {
            $unwind: {
                path: "$towers.towers",
            }
        },

        // Stage 3
        {
            $group: {
                _id: '$_id',
                buildType: {
                    $addToSet: '$towers.towers.buildType'
                }
            }
        },

    ]



);