问题描述
我的订单集合中的文档具有_client
键,这是一个ObjectId引用另一个集合中的另一个实体.该集合可能是组织,并且可能是用户-我的意思是-这是变量集合.我想告诉Mongo查找是否在两个集合中都找到了_client id.
My documents in the orders collection has _client
key, which is an ObjectId references to another entity in another collection.The collection could be organization and could be users - I mean - it's variable collection.I want to tell Mongo to lookup if the _client id is found in both collections.
{
$lookup: {
from: "users", // could be "organizations"
let: { "client": "$_client" }, // could be "_organization"
pipeline: [
{ $match: { $expr: { $eq: ["$_id", "$$client"] }}},
],
as: "client"
}
},
{
$unwind: "$client"
},
我尝试设置两次查找,一次用于 _client ,一次用于 _organization ,但是当其中之一丢失时,我没有得到任何结果全部.
I have tried to just set up two look ups, once for _client and one for _organization however when there one of them is missing, I just got no results at all.
推荐答案
$unwind
过滤掉数组为空且不包含任何元素的文档.
$unwind
filtered out the documents where arrays are empty and do not contain any element.
因此,您必须使用 preserveNullAndEmptyArrays
并将其设置为true
So, You have to use preserveNullAndEmptyArrays
and set it to true
{ "$unwind": { "path": "$client", "preserveNullAndEmptyArrays": true }}
,与organizations
{ "$unwind": { "path": "$organization", "preserveNullAndEmptyArrays": true }}
这篇关于来自可调整的国外集合的MongoDB聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!