1

I need to retrieve only records that have at least one element in the format.prices array and every elements price are between 0 and 0.99:

So this works fine for the price comparison:

{ 'formats.prices': { $not: { $elemMatch: { price: { $gt: 0, $lte: 0.99 } } } } }

But how can I add the condition like $not: { $size: 0 } to exclude also the formats.prices without elements at all?

0

1 Answer 1

1

Well, I ended with this and it works fine, don't know if there is a better way:

{
    'formats.prices': { $not: { $elemMatch: { price: { $gt: 0, $lte: 0.99 } } } },
    'formats.prices.0.price': { $exists: true }
}
Sign up to request clarification or add additional context in comments.

2 Comments

It's better like it is. Presuming you have an index on "formats.prices.price" ( which is probably a good idea considering you want to range query it anyway, albeit an exclusion right now ) then the $exists test here can actually use it, which $not: { $size: 0 } cannot. Seems though that for a positive price then it would be better to do a positive match { 'formats.prices.price': { $gt: 0.99 } } unless your true intention is that no price in the array falls in that range. Which is actually the oposite to how you posed your question.
Thanks you very much @BlakesSeven glad it is the best option, for the intention of the app yes I mistook the question, because I need that no price falls in that range (and not at least one). (Updating it)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.