Home > Blockchain >  Complex Conditional mongodb query to match value if exists
Complex Conditional mongodb query to match value if exists

Time:10-31

I'm trying a condition if it's possible or not needed some answers if it's can be done.

Let's say I have a collection named : Resturant


Resturant

  • id
  • name
  • food

so and i have 4 rows :

  • 1 , resturant1, burger
  • 2 , resturant2, sandwich
  • 3 , resturant2, burger
  • 4 , resturant3, burger

So what i'm trying to achieve here is from a single query to fetch resturant1 & resturan2 values like

{"$match": {"$expr": {"$in": ["resturant1", "resturant2"]}

but if the food already exists in resturant1 then don't fetch that value from resturant2 so if burger already exists in resturant1 then do not fetch it from resturant2. so the result will be only 2 rows :

  • 1 , resturant1, burger
  • 2 , resturant2, sandwich

We can achieve this after fetching the result and overriding the already exists values but i was seeing if we can use any condition in mongodb query itself.

CodePudding user response:

One option is using $setWindowFields (since mongodb version 5.0):

  1. $match the relevant documents by name
  2. Use $setWindowFields to temporarily add a set of all food types up to this document
  3. $match only documents with food that is not in the document food.
  4. Remove the added field
db.collection.aggregate([
  {$match: {name: {$in: ["resturant1", "resturant2"]}}},
  {$setWindowFields: {
      sortBy: {name: 1},
      output: {foodSet: {$addToSet: "$food", window: {documents: ["unbounded", -1]}}}
  }},
  {$match: {$expr: {$not: {$in: ["$food", "$foodSet"]}}}},
  {$unset: "foodSet"}
])

See how it works on the playground example

  • Related