MongoDB aggregate from adjustable foreign collections

僤鯓⒐⒋嵵緔 提交于 2020-01-04 07:43:21

问题


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"
  },

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.


回答1:


$unwind filtered out the documents where arrays are empty and do not contain any element.

So, You have to use preserveNullAndEmptyArrays and set it to true

{ "$unwind": { "path": "$client", "preserveNullAndEmptyArrays": true }}

and same for the or organizations

{ "$unwind": { "path": "$organization", "preserveNullAndEmptyArrays": true }}


来源:https://stackoverflow.com/questions/54615828/mongodb-aggregate-from-adjustable-foreign-collections

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!