Kunok
Kunok

Reputation: 8759

db.collection.group - display other attributes too

I have objects such as:

{
 foo: "A",
 bar: "Alpha"
},
{
 foo: "A",
 bar: "Alphabet"
},
{
 foo: "B",
 bar: "Beta"
}

I am using this query:

db.collectionName.group({
  key:{foo: 1}, 
  reduce: function(curr, result){}, 
  initial: {}
})

to group them by foo field. It returns object such as:

{
  foo: "A"
},
{
  foo: "B"
}

however I want them to display such as:

{
 foo: "A",
 bar: "Alpha"
},
{
 foo: "B",
 bar: "Beta"
}

It doesn't really matter which value will be shown in bar, but I need any value. If I would also include bar for the key param to the group attribute object, I would get many duplicates, but I only need uniques by foo field, while bar can be value from any of objects that match foo group.

Upvotes: 1

Views: 127

Answers (1)

chridam
chridam

Reputation: 103345

Use db.collection.aggregate() with the $group stage as:

db.collectionName.aggregate([
    {
        "$group": {
            "_id": "$foo",
            "bar": { "$first": "$bar" }
        }
    }
])

To get the exact output, push another $project pipeline stage to format your final output as:

db.collectionName.aggregate([
    {
        "$group": {
            "_id": "$foo",
            "bar": { "$first": "$bar" }
        }
    },
    {
        "$project": {
            "_id": 0,
            "foo": "$_id",
            "bar": 1
        }
    }
])

Upvotes: 2

Related Questions