[英]Sort/Group by the number of documents with equal fields in MongoDB
What I want to achieve is grouping these documents, 我要实现的是将这些文档分组,
{voteid: A, userid: x}, {voteid: C, userid: x},
{voteid: A, userid: y}, {voteid: A, userid: z},
{voteid: C, userid: z}, {voteid: D, userid: z}
in objects with number of votes (users are irreleveant here) and also sorting them based on voteid : 在具有投票数的对象中(用户在这里是无关紧要的),并且还基于投票id对它们进行排序 :
{voteid: A, votes: 3},
{voteid: C, votes: 2},
{voteid: D, votes: 1}
How should I approach that? 我应该如何处理?
I'm working with MongoDB 3.0 Node.js driver 我正在使用MongoDB 3.0 Node.js驱动程序
Okay, so this will help you do your query (count) and sort them for voteid
, 好的,这样可以帮助您进行查询(计数)并对它们进行voteid
排序,
db.yourCollection.aggregate([{
$group: {
_id: '$voteid',
votes: {$sum: 1}
}
},
{
$sort: {
_id: 1
}
},
{
$project: {
_id: 0,
voteid: '$_id',
votes: 1
}
}
])
What we are doing here is first apply $group
operator on the records and find all the occurences of the voteid
by assigining it to _id
as accumulator object and subsequently storing count values -- {$sum: 1}
in votes
. 我们在这里要做的是首先在记录上应用$group
运算符,并通过将voteid
ID辅助到作为累加器对象的_id
,然后将计数值- {$sum: 1}
在votes
,找到所有voteid
的出现。
Then, we sort based on _id
we just created with votesid
and then project the result in the form we needed -- eliminating _id
and remapping the previous group _id
to voteid
and allowing votes in our result. 然后,我们的排序基于_id
我们只是创建votesid
然后投射的结果,我们需要的形式-消除_id
和重映射前一组_id
到voteid
并允许票我们的结果。
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.