Reputation: 91959
I have a collection called contract
and I would like to group using "a_id"
{
a_id: 1,
"name": "n1"
}
{
a_id: 2,
"name": "n2"
}
{
a_id: 1,
"name": "n3"
}
{
a_id: 1,
"name": "n4"
}
{
a_id: 2,
"name": "n5"
}
I want to group by "a_id"
to show me the list of names associated.
{
a_id: 1,
values: ["n1", "n3", "n4"]
}
{
a_id: 2,
values: ["n2", "n5"]
}
My code:
db.contract.group({
key:{a_id: 1},
initial: {v: ''},
reduce: function(doc, obj){
v = v + " " + obj.name
}
});
My Output:
{
"a_id" : 1,
"v" : ""
},
{
"asset_id" : 2,
"v" : ""
}
This doesn't return the list of values, but mongd logs shows me list of names, How can I correct this?
Fixed
db.contract.group({
key:{a_id: 1},
initial: {v: []},
reduce: function(obj, prev){
prev.v.push(obj.name)
}
});
Upvotes: 5
Views: 4177
Reputation: 141
You could also use MongoDB's aggregation framework:
The following will work exactly the same:
db.contract.aggregate({$group: { '_id': '$a_id', 'name': { $push: '$name'}}})
The following will put every unique value only once in the result set (in case there are duplicated names per 'a_id'):
db.contract.aggregate({$group: { '_id': '$a_id', 'name': { $addToSet: '$name'}}})
Upvotes: 14
Reputation: 91959
Fixed
db.contract.group({
key:{a_id: 1},
initial: {v: []},
reduce: function(obj, prev){
prev.v.push(obj.name)
}
});
Upvotes: 1