1

If I had a collection of documents like the following:

{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'}

What would be the most efficient mongo query to get all the unique combinations of the attributes a, b, c? Is it possible? The result looking something like:

{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:*}

* = don't care

Thanks, your help is appreciated.

Patrick Lorio
  • 5,520
  • 11
  • 45
  • 74

2 Answers2

1

The usual tool for this kind of operation is the distinct function. Unfortunately, MongoDB's distinct can only filter on one field (e.g. db.collection.distinct("a")). Various work-around are possible, for example using aggregate or group.

Example with aggregate:

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

You will have to extract the information from the result, but I guess this is not a huge problem.

Example with group:

db.collection.group({
    key: {
        a: 1, 
        b: 1,
        c: 1
    }, 
    reduce: function (current, result) {}, 
    initial: {}
})
Martin Maillard
  • 2,751
  • 19
  • 24
0

you could try something like this

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

also try this link mongodb get distinct records

I'm not MongoDB professional, but I think you also can use js function, like this:

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);
        }
    }
)
Community
  • 1
  • 1
Roman Pekar
  • 107,110
  • 28
  • 195
  • 197