Eugene Yu
Eugene Yu

Reputation: 3968

MongoDB: how to query with a specific rule for a specific element in $in?

Honestly I doubt that it is possible but just giving a shot here.

Here's an example of DB records

{
    type: 'fruit',
    name: 'apple',
    quantity: 3
}
{
    type: 'fruit',
    name: 'orange',
    quantity: 10
}
{
    type: 'vegetable',
    name: 'tomato',
    quantity: 4
}
{
    type: 'meat',
    name: 'beef',
    quantity: 2
}

then here's the query

{type: { $in: ['fruit', 'vegetable', 'meat']}}

So this will return all of the records in collection 'apple', 'orange', 'tomato', 'beef'.

I would like to query 'fruit', 'vegetable', 'meat' and also the records that have quantities more than 5 for 'fruit' only but not others. So the result will be

orange, tomato, beef

Not sure my explanation makes sense but is this a possible query? or I should go query twice? Thanks for reading.

Upvotes: 0

Views: 38

Answers (1)

user2941651
user2941651

Reputation:

Please try:

{ 
    $or: [
        { type: { $in: ['vegetable', 'meat'] } },
        { type: { $in: ['fruit'] }, quantity: { $gt: 5 } } 
    ]
}

I hope that helps.

Upvotes: 1

Related Questions