MongoDB 对孩子进行排序 [英] MongoDB sorting on children
问题描述
我有以下文件:
{'_id':'id1','parentId':"",'count':1}
{'_id':'id2','parentId':"",'count':12}
{'_id':'id3','parentId':"",'count':16}
{'_id':'id4','parentId':"id2",'count':3}
{'_id':'id5','parentId':"id2",'count':3}
{'_id':'id6','parentId':"id1",'count':0
{'_id':'id7','parentId':"id1",'count':122}
带有 "" 字段的 parentId 表示父节点.如果 parentId 存在,则表示给定的 parentId 的子节点.我需要一个将按计数"(降序)排序的查询,但是我只希望它返回 parentId 的游标.但是,如果子项计数最高,则表示总体上的最高值,并且应返回该子项的父项.
parentId with a "" field represents a parent node. If the parentId is present this signifies a child node of the parentId given. I need a query that will sort on the 'count' (descending) however I only want it to return a cursor of parentId. However if a child count is the highest this represent the highest value overall and the parent of that child should be returned.
对上述数据运行查询的结果应该按以下顺序给我文档:id1, id3 ,id2
The result of running the query on the above data should give me the documents in the following order: id1, id3 ,id2
我想过启动聚合管道.对于第一阶段,我可以按计数进行排序.但是我不知道如何让查询返回孩子的 parentId...
I thought about starting an aggregation pipeline. For the first stage I can do a sort on count. However I don't know how i can get the query to return the parentId for a child...
推荐答案
您可以通过以下聚合来实现:
You can do it with the following aggregation:
db.collection.aggregate(
[
{
$project: {
group_id : { $cond : { if: { $ne: [ "$parentId", "" ] }, then: "$parentId", else: "$_id" }},
count :1
}
},
{
$group: {
_id : "$group_id",
total_count : { $sum: "$count" }
}
},
{
$sort: {
total_count : -1
}
}
]
);
首先,我投影了一个额外的字段group_id",它根据 parentId 值填充了 _id 或 parentId.group_id 字段用于分组和统计总数.最后一步是对 total_count 进行分组.
First i project an extra field "group_id" which is filled with the _id or the parentId depending of the parentId value. The group_id field is used to group and make a total count. Last step is to group on the total_count.
当您使用 mongoDb 3.4 时,您可以查看 $graphLookup 但现在我留给你的是 pre 3.4 聚合 ;-)
When you are using mongoDb 3.4 you could check out $graphLookup but for now i leave you with the pre 3.4 aggregation ;-)
这篇关于MongoDB 对孩子进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!