使用 MongoDB 根据该记录的值获取不同的记录
Fetch distinct record based on values for that record with MongoDB
我有 collection 家餐厅记录。这 collection 中的一些餐厅属于某个集团(连锁餐厅,例如 KfC 等),而其他则没有任何集团(个人餐厅,不属于任何链)。
示例:
餐厅collection
{_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"}
链collection:
{_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)
您可以为此使用聚合框架。聚合管道的第一步是 $match
operator that filters the restaurants on the address. The $group
pipeline stage will then group the filtered documents by the chain_id
key and applies the accumulator expression $first
to the $$ROOT
system variable on each group. You can the reshape the documents using the $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
}
我有 collection 家餐厅记录。这 collection 中的一些餐厅属于某个集团(连锁餐厅,例如 KfC 等),而其他则没有任何集团(个人餐厅,不属于任何链)。
示例:
餐厅collection
{_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"}
链collection:
{_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)
您可以为此使用聚合框架。聚合管道的第一步是 $match
operator that filters the restaurants on the address. The $group
pipeline stage will then group the filtered documents by the chain_id
key and applies the accumulator expression $first
to the $$ROOT
system variable on each group. You can the reshape the documents using the $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
}