简体   繁体   中英

Mongoose - condition that is valid for all elements in nested array

My documents have a nested array of objects. One field of those "item" objects is "totalPrice".

I want to be able to filter the documents in a way that it only returns docs which has an items array that completely fulfills the filter, meaning that each object in the array has a lower price than the filter.

My current query looks like this:

MyObjModel.find({"items.totalPrice": { $lt: 100 } })

My expectation would be that it only returns documents where each item has a price smaller than 100. However, it returns documents where only one array item fulfills the requirement, so it would return this one although the second item does not fulfill the query.

{
   items: [{totalPrice: 88}, {totalPrice: 120}]
}

How would I have to change my query object?

Instead of finding documents where each item has a price smaller than 100, you can find documents where no item has price bigger than or equal 100.

Model.find({'items.totalPrice': {$not: {$gte: 100}}})

Mongo Playground

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