如何在 MongoDB 中应用 $lookup,如果第二个集合上的记录被删除仍然给出第一个集合的所有记录的响应
How to apply $lookup in MongoDB, If the record on the second collection is deleted still give the response all the record of the first collection
如何在 MongoDB 中应用 $lookup,如果删除了第二个集合中的记录,仍会给出第一个集合中所有记录的响应,如给定示例所示
第一集
A: [
{ _id : "a" , P : "dljslfsdjf" },
{ _id : "b" , P : "dljslfsdjf" },
{ _id : "c" , P : "dljslfsdjf" },
{ _id : "d" , P : "dljslfsdjf" }
]
第二集
B: [
{A _id : "a" , Q : "dljslfsdjf" },
{A_id : "b" , Q : "dljslfsdjf" },
{ A_id : "c" , Q : "dljslfsdjf" }
]
需要回复 --
C: [
{ _id : "a" , P : "dljslfsdjf", BB: {A _id : "a" , Q : "dljslfsdjf" } },
{ _id : "b" , P : "dljslfsdjf", BB : {A_id : "b" , Q : "dljslfsdjf" } },
{ _id : "c" , P : "dljslfsdjf", BB : { A_id : "c" , Q : "dljslfsdjf" } },
{ _id : "d" , P : "dljslfsdjf", BB: {**anything that indicates record not found**} }
]
我写一个查询--
db.A.aggregate([
{
$match: {
P : "dljslfsdjf"
}
},
{
$lookup : {
from : "B",
localField : "_id",
foreignField : "A_id",
as : "BB"
}
}
{
$unwind : "$BB"
}
])
它 return 只是树记录,return 不是--
_id : "d" , P : "dljslfsdjf", BB: {**anything that indicate record not found**}
$unwind
默认行为是在解构时删除 null 或空数组。如果您需要保留空数组或空值
{$unwind:{ path: "$BB",preserveNullAndEmptyArrays: true}}
。参考 $unwind
如何在 MongoDB 中应用 $lookup,如果删除了第二个集合中的记录,仍会给出第一个集合中所有记录的响应,如给定示例所示
第一集
A: [
{ _id : "a" , P : "dljslfsdjf" },
{ _id : "b" , P : "dljslfsdjf" },
{ _id : "c" , P : "dljslfsdjf" },
{ _id : "d" , P : "dljslfsdjf" }
]
第二集
B: [
{A _id : "a" , Q : "dljslfsdjf" },
{A_id : "b" , Q : "dljslfsdjf" },
{ A_id : "c" , Q : "dljslfsdjf" }
]
需要回复 --
C: [
{ _id : "a" , P : "dljslfsdjf", BB: {A _id : "a" , Q : "dljslfsdjf" } },
{ _id : "b" , P : "dljslfsdjf", BB : {A_id : "b" , Q : "dljslfsdjf" } },
{ _id : "c" , P : "dljslfsdjf", BB : { A_id : "c" , Q : "dljslfsdjf" } },
{ _id : "d" , P : "dljslfsdjf", BB: {**anything that indicates record not found**} }
]
我写一个查询--
db.A.aggregate([
{
$match: {
P : "dljslfsdjf"
}
},
{
$lookup : {
from : "B",
localField : "_id",
foreignField : "A_id",
as : "BB"
}
}
{
$unwind : "$BB"
}
])
它 return 只是树记录,return 不是--
_id : "d" , P : "dljslfsdjf", BB: {**anything that indicate record not found**}
$unwind
默认行为是在解构时删除 null 或空数组。如果您需要保留空数组或空值
{$unwind:{ path: "$BB",preserveNullAndEmptyArrays: true}}
。参考 $unwind