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):
$matchthe relevant documents byname- Use
$setWindowFieldsto temporarily add a set of allfoodtypes up to this document $matchonly documents withfoodthat is not in the documentfood.- 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
