我来自SQL世界并从MongoDB开始,我仍然有点困惑...... 我有一个这种结构的集合
{
"_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",
}
和我的查询,
db.getCollection('stores').aggregate([{"$group":{"_id" : {city :"$city", company : "$company"}}}])
我使用angular和NodejS + Express从de数据库获取数据,我得到了这种格式的数据
[
{
_id:{
city:"City1",
company:"Compnay1"
}
},
{
_id:{
city:"City1",
company:"Company2"
}
},
{
_id:{
city:"City2",
company:"Compan1"
}
}
]
所以我想知道是否有办法在没有_id键的情况下获得此查询结果,
像这样: [
{
city:"City1",
company:"Compnay1"
},
{
city:"City1",
company:"Company2"
},
{
city:"City2",
company:"Compan1"
}
]
答案 0 :(得分:3)
在下一个管道阶段使用$project
作为聚合管道运算符:
db.getCollection('stores').aggregate([
{"$group":{"_id" : {city :"$city", company : "$company"}}},
{"$project": {"city": "$_id.city", "company": "$_id.company", "_id": 0}}
])