1

我试图设置一个简单的要点来解释我的问题以及我想要什么

它绝对不会复制我的确切文档结构(这是完全不同的),但会帮助您轻松理解我的问题。

更新:

Gist 被意外删除,因此用问题更新了问题:

假设我有这个结构

    _id  name  birthdate
    ...  john  10 aug
    ...  doe   11 aug
    ...  foo   11 aug
    ...  bar   12 aug
    ...  baz   12 aug
    ...  bak   12 aug
    ...  buzz  13 aug

我想找到所有具有相同生日的文档,所以我的结果集会在那里:

    _id  name  birthdate
    ...  doe   11 aug
    ...  foo   11 aug
    ...  bar   12 aug
    ...  baz   12 aug
    ...  bak   12 aug

我还想以某种方式获取每个文档的日期共享记录的 count() 。所以,像这样

    _id  name  birthdate  count
    ...  doe   11 aug     2
    ...  foo   11 aug     2
    ...  bar   12 aug     3
    ...  baz   12 aug     3
    ...  bak   12 aug     3

到目前为止,我所尝试的只是 mapReduce,但我只能得到:

    _id     value
    11 aug  {count: 2}
    12 aug  {count: 3}
4

1 回答 1

3

使用MongoDB 2.2 中的新聚合框架可以更轻松地实现您的结果。

下面的示例使用 MongoDB shell,但类似的方法也适用于 Mongoid。

假设数据设置为:

db.users.insert({'name': 'john', 'birthdate':'10 aug'});
db.users.insert({'name': 'doe',  'birthdate':'11 aug'});
db.users.insert({'name': 'foo',  'birthdate':'11 aug'});
db.users.insert({'name': 'bar',  'birthdate':'12 aug'});
db.users.insert({'name': 'baz',  'birthdate':'12 aug'});
db.users.insert({'name': 'bak',  'birthdate':'12 aug'});
db.users.insert({'name': 'buzz', 'birthdate':'13 aug'});

以下是聚合命令的注释示例:

db.users.aggregate(
    // Group and count documents by same birthdate
    { $group: {
        '_id' : '$birthdate',
        'name': { $addToSet: '$name' },
        'count': { $sum: 1 },
    }},

    // Only match documents with at least one duplicate
    { $match : {
        'count' : { $gt: 1 }
    }},

    // Unwind the grouped documents so there is one per name
    { $unwind : '$name' },

    // Sort results by _id and name
    { $sort : {
        '_id': 1,
        'name': 1,
    }}
)

..和结果:

{
    "result" : [
        {
            "_id" : "11 aug",
            "name" : "doe",
            "count" : 2
        },
        {
            "_id" : "11 aug",
            "name" : "foo",
            "count" : 2
        },
        {
            "_id" : "12 aug",
            "name" : "bak",
            "count" : 3
        },
        {
            "_id" : "12 aug",
            "name" : "bar",
            "count" : 3
        },
        {
            "_id" : "12 aug",
            "name" : "baz",
            "count" : 3
        }
    ],
    "ok" : 1
}
于 2012-09-11T13:20:34.490 回答