din*_*wis 5 mongodb aggregation-framework
在这里,我使用 $lookup 到其他集合的左连接,查询工作正常,但是当某些记录缺少值时,它会返回
errmsg : $in requires an array as a second argument, found: null
查询文档结构如下:
{
"no" : "2020921008981",
"sale" : {
"soldItems" : [
{
"itemId" : "5b55ac7f0550de00210a3b24",
},
{
"itemId" : "5b55ac7f0550de00215584re",
}
],
"bills" : [
{
"billNo" : "2020921053467",
"insurancePlanId" : "160",
},
{
"billNo" : "2020921053467",
"insurancePlanId" : "170",
}
],
"visitIds" : [
5b55ac7f0550de00210a3b24, 5b55ac7f0550de00210a3b24
]
}
}
Run Code Online (Sandbox Code Playgroud)
查询:
db.case.aggregate([
{
$lookup: {
from: "insurance",
let: { ipids: "$sale.bill.insurancePlanId" },
pipeline: [
{
$unwind: "$coveragePlans"
},
{
$match: { $expr: { $in: ["$coveragePlans._id", "$$ipids"] } }
},
{
$project: { _id: 0, name: 1 }
}
],
as: "insurances"
}
},
{
$lookup: {
from: "item",
let: { iid: "$salesOrder.purchaseItems.itemRefId" },
pipeline: [
{
$match: {
$expr: {
$in: ["$_id", {
$map: {
input: "$$iid",
in: { $toObjectId: "$$this" }
}
}
]
}
}
}
],
as: "items"
}
}
])
Run Code Online (Sandbox Code Playgroud)
保险收取:
{
"_id" : ObjectId("5b55aca20550de00210a6d25"),
"name" : "HIJKL"
"coveragePlans" : [
{
"_id" : "160",
"name" : "UVWZ",
},
{
"_id" : "161",
"name" : "LMNO",
}
]
},
{
"_id" : ObjectId("5b55aca20550de00210a6d25"),
"name" : "WXYZ"
"coveragePlans" : [
{
"_id" : "169",
"name" : "5ABC",
},
{
"_id" : "170",
"name" : "4XYZ",
}
]
}
Run Code Online (Sandbox Code Playgroud)
物品收藏:
{
"_id" : ObjectId("5b55ac7f0550de00210a3b24"),
"code" : "ABCDE"
},
{
"_id" : ObjectId("5b55ac7f0550de00215584re"),
"code" : "PQRST"
}
Run Code Online (Sandbox Code Playgroud)
如何避免这种情况并在管道进入下一阶段之前有效地进行空检查?尝试过,{ $match: { "fieldName": { $exists: true, $ne: null } } }但它返回有关格式的 mongo 错误。如果这是要走的路,请提及我应该放置的阶段..提前致谢
您可以使用$ifNull运算符
let: { ipids: {$ifNull:["$sale.bill.insurancePlanId", [] ]} },
Run Code Online (Sandbox Code Playgroud)
编辑:跳过空"$salesOrder.purchaseItems.itemRefId"值
let: { iid: {$filter: {input:"$salesOrder.purchaseItems.itemRefId", cond:{$ne:["$$this", ""]}}} },
Run Code Online (Sandbox Code Playgroud)