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)
}
});
Fixed