Mongodb 如何聚合嵌套文档?
我有一个收藏:Mongodb 如何聚合嵌套文档?,mongodb,nested,aggregation-framework,Mongodb,Nested,Aggregation Framework,我有一个收藏: { _id : xxx, children : [ { childrenOfChildren : [ { price : xxx }, { price : xxx }, {
{
_id : xxx,
children : [
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
},
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
},
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
}
]
},
{
_id : xxx,
children : [
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
},
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
},
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
}
]
},
{
_id : xxx,
children : [
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
},
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
},
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
}
]
},
{
_id : xxx,
children : [
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
},
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
},
{
childrenOfChildren : [
{
price : xxx
},
{
price : xxx
},
{
price : xxx
}
]
}
]
}
每个条目都有一个名为children的数组。并且children中的每个条目都有一个名为childrenOfChildren的数组。childrenOfChildren中的每个条目都有一个名为price的属性。我想在整个系列中获得最大的价格价值。我怎样才能做到这一点?请帮帮我 您可以通过使用
聚合查询$unwind
和$group
从整体收集中获取最高价格
您可以尝试以下查询:
db.getCollection('collectionName').aggregate([
{$unwind: "$children"},
{$unwind: "$children.childrenOfChildren"},
{$group:{_id: null, price:{$max: "$children.childrenOfChildren.price"}}}
])
您可以使用$unwind和$group执行此操作
db.collection.aggregate([
{
$unwind:"$children"
},
{
$unwind:"$children.childrenOfChildren"
},
{
$group:{
_id:null,
maxPrice:{
$max:"$children.childrenOfChildren.price"
}
}
}
])
输出:
{ "_id" : null, "maxPrice" : 110 }
在线试用:可以尝试使用聚合
查询可能重复的