我收集了餐厅记录。这个系列中的一些餐馆属于某个团体(连锁餐厅,例如KfC等),而其他没有任何团体(个别餐厅,不属于任何连锁店。)
示例:
餐厅藏品
{_id:"1",title:"rest1",address:"somethingx",chain_id:"123"},
{_id:"2",title:"rest2",address:"somethingx",chain_id:"123"},
{_id:"3",title:"rest3",address:"somethingy",chain_id:"0"},
{_id:"4",title:"rest4",address:"somethingx",chain_id:"0"}
连锁收藏:
{_id:"123",chain_name:"VSWEETS",address_deatils:[
{restID:"",address:"somethingx"},
{restID:"",address:"somethingx"}
]
}
{_id:"456",chain_name:"KFC",address_deatils:[]}
我需要使用类似的chain_id获取不同的餐厅,即如果它属于某个链条,则只有单个餐厅应该来(chain_id!= 0)
答案 0 :(得分:3)
您可以使用聚合框架。聚合管道将作为 $match
运算符的第一步,过滤地址上的餐馆。然后, $group
管道阶段将按chain_id
键对过滤后的文档进行分组,并将累加器表达式 $first
应用于 $$ROOT
每个组的系统变量。您可以使用$project
管道阶段重新整理文档。
为您提供所需结果的最终聚合管道如下:
db.restaurant.aggregate([
{
"$match": { "address" : "somethingx" }
},
{
"$group": {
"_id": "$chain_id",
"data": { "$first": "$$ROOT" }
}
},
{
"$project": {
"_id" : "$data._id",
"title" : "$data.title",
"address" : "$data.address",
"chain_id" : "$data.chain_id"
}
}
])
<强>输出强>:
/* 0 */
{
"result" : [
{
"_id" : "4",
"title" : "rest4",
"address" : "somethingx",
"chain_id" : "0"
},
{
"_id" : "1",
"title" : "rest1",
"address" : "somethingx",
"chain_id" : "123"
}
],
"ok" : 1
}