Diego Vega Diego Vega - 5 months ago 28
AngularJS Question

Reformat MongoDB results from aggregate

I'm coming from SQL world and starting with MongoDB, I'm still a bit confused...
I have a collection with this structure

{
"_id" : ObjectId("5769b51f675e6190119935ec"),
"city" : "City1",
"company" : "Company1",
"country" : "Country1",
"zip" : "23345",
},{
"_id" : ObjectId("5769b51f675e6190119935ed"),
"city" : "City1",
"company" : "Company2",
"country" : "Country1",
"zip" : "1245",
},{
"_id" : ObjectId("5769b51f675e6190119935ee"),
"city" : "City2",
"company" : "Company1",
"country" : "Country1",
"zip" : "123445",
},{
"_id" : ObjectId("5769b51f675e6190119935ef"),
"city" : "City1",
"company" : "Company2",
"country" : "Country1",
"zip" : "1235445",
}


and my query,

db.getCollection('stores').aggregate([{"$group":{"_id" : {city :"$city", company : "$company"}}}])


I'm using angular and NodejS+Express to get the data from de database and I get the data with this format

[
{
_id:{
city:"City1",
company:"Compnay1"
}
},
{
_id:{
city:"City1",
company:"Company2"
}
},
{
_id:{
city:"City2",
company:"Compan1"
}
}
]


So I'm wondering if there's a way to get this query result without the _id key,

like this:

[
{
city:"City1",
company:"Compnay1"
},
{
city:"City1",
company:"Company2"
},
{
city:"City2",
company:"Compan1"
}
]

Answer

Just use $project as aggregation pipeline operator in the next pipeline stage:

db.getCollection('stores').aggregate([
  {"$group":{"_id" : {city :"$city", company : "$company"}}},
  {"$project": {"city": "$_id.city", "company": "$_id.company", "_id": 0}}
])
Comments