在MongoDB中按属性值分组(并计数?) [英] Grouping by property value (and counting?) in MongoDB

查看:567
本文介绍了在MongoDB中按属性值分组(并计数?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将Meteor用于一个网络项目,我需要找到一种方法来按其属性之一对集合中的记录进行分组(和计数)。这是我希望从中进行收集的样本记录中的一个示例记录:

I'm using Meteor for a web project, and I need to find a way to group (and count) records in a collection by one of their properties. This is a sample record from the Collection that I ned to do this from:

{
    "owner" : "7YnNwSC3E3iTcRHcC",
    "isbn" : "1551110881",
    "title" : "Introduction",
    "type" : "0",
    "class" : "ADNR1234",
    "condition" : "0",
    "active" : false,
    "createdAt" : ISODate("2014-08-18T15:38:30.012Z"),
    "tradeFor" : {
        "isbn" : "7463849506",
        "title" : "Intro 2"
    },
    "_id" : "RFzvEdLkYxt5EmQ7s"
}

我知道我需要找出一种方法...我想这叫做聚合?无论如何...我需要使用的属性是类。我需要一种方法来遍历整个集合,并让我输出每个类(ADNR1234),并将每个使用的类作为值的记录数。

I know I will need to figure out a way to do...I guess it's called aggregation? Anyway...the property I'm needing to use is "class". I need a way to go through the whole collection and let me output each class (ADNR1234) with the number of records that have each used class as a value.

我希望我并不是很想问这个问题,我是Meteor的新手,这似乎是要解决的怪异问题。

I hope I didn't ask this question poorly, I'm sort of new to Meteor, and this seems like a sort of weird problem to try to solve.

推荐答案

Meteor通过MongoInternals公开了来自节点驱动程序的mongo连接,因此您可以使用它来调用聚合。

Meteor exposes the mongo connection from the node driver with MongoInternals so you can use that to call aggregate.

var db = MongoInternals.defaultRemoteCollectionDriver().mongo.db;
var col = db.collection( 'yourCollection' );
var aggregateSync = Meteor._wrapAsync( col.aggregate.bind( col ) );
var pipeline = [{$match: {}},{$group: {_id: '$class', count:{$sum: 1}}} ];
var theAnswer = aggregateSync( pipeline );

聚合管道还允许您根据需要应用排序和限制之类的东西。

Documentation on aggregation pipeline also lets you apply things like sort and limit if you need them.

已更新:通过使用 $ match 选择文档来更正管道数组。在流星垫中查找工作代码。

updated: Pipeline array corrected by using $match to select docs. Working code up at Meteor Pad.

这篇关于在MongoDB中按属性值分组(并计数?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆