我已经在线搜索过,但找不到与我的情况相符的内容。这是情况。
我正在使用汇总将一个集合和另一个集合中的一个文档组合在一起
restaurants.aggregate([
{
$match: {
_id: {
$in: idList
}
}
},
{
$lookup: {
from: "tags",
localField: "details.restaurantType",
foreignField: "details.restaurantType._id",
as: "types"
}
},
{
$project: {
restaurantName: "$details.restaurantName",
restaurantType: "$details.restaurantType",
type: {
$filter: {
input: "$types",
as: "type",
cond: {
$eq: ["$$type._id", "$details.restaurantType"]
}
}
},
currency: "$details.currency",
costPerPax: "$details.costPerPax"
}
}
]);
当前结果中的“类型”字段为[],我需要一个匹配的值
[
{
"id": "5c20c7a0036dda80a8baabcc",
"restaurantName": "Villagio Restaurant Sutera Mall",
"type": [],
"currency": "RM",
"costPerPax": 22,
},
{
"id": "5c20ceb07715216d3c217b7a",
"restaurantName": "Thai Food Thai Now Sutera Mall",
"type": [],
"currency": "RM",
"costPerPax": 16,
}
]
我需要“类型”字段具有类似这样的其他集合中的匹配标签名称
[
{
"id": "5c20c7a0036dda80a8baabcc",
"restaurantName": "Villagio Restaurant Sutera Mall",
"type": "Western",
"currency": "RM",
"costPerPax": 22,
},
{
"id": "5c20ceb07715216d3c217b7a",
"restaurantName": "Thai Food Thai Now Sutera Mall",
"type": "Thai",
"currency": "RM",
"costPerPax": 16,
}
]
餐厅收藏中的两个文件
{
"details": {
"restaurantName": "Villagio Restaurant Sutera Mall",
"restaurantType": "5c01fb57497a896d50f498a8"
},
"_id": "5c20c7a0036dda80a8baabcc",
"status": "OP",
"__v": 0
},
{
"details": {
"restaurantName": "Kingshahi Japanese Shop",
"restaurantType": "5c01fb57497a896d50f49879"
},
"_id": "5c20cb4fb7e75180480690c2",
"status": "OP",
"__v": 0
}
标签收集中的一个文档
{
"_id": "5c01fb57497a896d50f49876",
"details": {
"restaurantTypeId": "5c01fb57497a896d50f49877",
"restaurantTypes": [
{
"_id": "5c01fb57497a896d50f49879",
"name": "Asian",
"counter": 1
},
{
"_id": "5c01fb57497a896d50f4987a",
"name": "Bakery",
"counter": 0
}
]
}
}
答案 0 :(得分:3)
您可以使用以下优化的聚合管道
db.restaurants.aggregate([
{ "$lookup": {
"from": "tags",
"let": { "restaurantType": "$details.restaurantType" },
"pipeline": [
{ "$match": {
"$expr": { "$in": ["$$restaurantType", "$details.restaurantTypes._id"] }
}},
{ "$unwind": "$details.restaurantTypes" },
{ "$match": {
"$expr": { "$eq": ["$details.restaurantTypes._id", "$$restaurantType"] }
}}
],
"as": "types"
}},
{ "$project": {
"restaurantName": "$details.restaurantName",
"restaurantType": "$details.restaurantType",
"type": { "$arrayElemAt": ["$types.details.restaurantTypes.name", 0] },
"currency": "$details.currency",
"costPerPax": "$details.costPerPax"
}}
])