mongo选择文档属性的所有唯一组合

时间:2013-07-12 13:32:41

标签: python mongodb

如果我收集了以下文件:

{a:'1', b:'2', c:'3', d:'a'},
{a:'1', b:'2', c:'1', d:'b'},
{a:'1', b:'2', c:'3', d:'c'},
{a:'1', b:'3', c:'1', d:'d'},
{a:'1', b:'2', c:'3', d:'e'},
{a:'2', b:'2', c:'1', d:'f'}

获得属性a,b,c的所有唯一组合的最有效的mongo查询是什么?可能吗?结果看起来像:

{a:'1', b:'2', c:'3', d:*},
{a:'1', b:'2', c:'1', d:*},
{a:'1', b:'3', c:'1', d:*},
{a:'2', b:'2', c:'1', d:*}

* =不在乎

谢谢,感谢您的帮助。

2 个答案:

答案 0 :(得分:0)

你可以尝试这样的事情

db.<your collection>.aggregate([{$group:{"a": "$a", "b": "$b", "c": "$c"}}])

也可以尝试此链接mongodb get distinct records

我不是MongoDB的专业人士,但我认为你也可以使用js功能,如下所示:

a = {}
db.<your collection>.find().forEach(
    function(x)
    {
        if (a[[x.a, x.b, x.c]] == null) {
            a[[x.a, x.b, x.c]] = true;
            printjson(x);
        }
    }
)

答案 1 :(得分:0)

此类操作的常用工具是distinct功能。不幸的是,MongoDB的distinct只能过滤一个字段(例如db.collection.distinct("a"))。可以使用各种解决方法,例如使用aggregategroup

aggregate示例:

db.collection.aggregate({
    $group: {
        _id: {
            a: "$a", 
            b: "$b", 
            c: "$c"
        }
    }
})

您必须从结果中提取信息,但我想这不是一个大问题。

group示例:

db.collection.group({
    key: {
        a: 1, 
        b: 1,
        c: 1
    }, 
    reduce: function (current, result) {}, 
    initial: {}
})