简体   繁体   中英

MongoDB aggregate from adjustable foreign collections

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.

$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 }}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM