简体   繁体   中英

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.

Please try:

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

I hope that helps.

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