2

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.

Ashh
  • 44,693
  • 14
  • 105
  • 132
Raz Buchnik
  • 7,753
  • 14
  • 53
  • 96

1 Answers1

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 }}
Ashh
  • 44,693
  • 14
  • 105
  • 132