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”的所有可能值,比如:
- 公寓
- 房子
- 办公室
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'
}
}
},
]
);