我有這兩個簡單的集合:
專案:
{
"id" : "111",
"name" : "apple",
"status" : "active"
}
{
"id" : "222",
"name" : "banana",
"status" : "active"
}
存貨:
{
"item_id" : "111",
"qty" : 3,
"branch" : "main"
}
{
"item_id" : "222",
"qty" : 3
}
現在我只想回傳具有“status”==“active”和“branch”存在且等于庫存集合中的“main”的專案。我在下面有這段代碼,但它回傳所有檔案,第二個檔案有一個空的“資訊”陣列。
db.getCollection('items')
.aggregate([
{$match:{$and:[
{"status":'active'},
{"name":{$exists:true}}
]
}},
{$lookup:{
as:"info",
from:"inventory",
let:{fruitId:"$id"},
pipeline:[
{$match:{
$and:[
{$expr:{$eq:["$item_id","$$fruitId"]}},
{"branch":{$eq:"main"}},
{"branch":{$exists:true}}
]
}
}
]
}}
])
誰能給我一個關于如何解決這個問題的想法?
uj5u.com熱心網友回復:
您的代碼運行良好。我認為您只需要$match在管道的最后一個階段。
db.items.aggregate([
{
$match: {
$and: [
{ "status": "active" },
{ "name": { $exists: true } }
]
}
},
{
$lookup: {
as: "info",
from: "inventory",
let: { fruitId: "$id" },
pipeline: [
{
$match: {
$and: [
{ $expr: { $eq: [ "$item_id", "$$fruitId" ] } },
{ "branch": { $eq: "main" } },
{ "branch": { $exists: true } }
]
}
}
]
}
},
{
"$match": {
"info": { "$ne": [] }
}
}
])
mongoplayground
uj5u.com熱心網友回復:
詢問
- 匹配
- 查找
id/item_id,并將分支與“main”匹配(如果它不存在,無論如何它都是假的) - 只保留不為空的
*query 與@YuTing 幾乎相同,但我還是寫了它,所以我發送它,因為替代查找語法的細微差別
測驗代碼在這里
items.aggregate(
[{"$match":
{"$expr":
{"$and":
[{"$eq":["$status", "active"]},
{"$ne":[{"$type":"$name"}, "missing"]}]}}},
{"$lookup":
{"from":"inventory",
"localField":"id",
"foreignField":"item_id",
"pipeline":[{"$match":{"$expr":{"$eq":["$branch", "main"]}}}],
"as":"inventory"}},
{"$match":{"$expr":{"$ne":["$inventory", []]}}},
{"$unset":["inventory"]}])
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/431849.html
