简体   繁体   English

Mongoose - 对嵌套数组中的所有元素都有效的条件

[英]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".这些“item”对象的一个​​字段是“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.我希望能够以一种方式过滤文档,它只返回具有完全满足过滤器的 items 数组的文档,这意味着数组中的每个对象的价格都低于过滤器。

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.我的期望是它只返回每个项目的价格小于 100 的文档。但是,它返回只有一个数组项目满足要求的文档,所以它会返回这个,尽管第二个项目不满足查询。

{
   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.您可以查找没有商品价格大于或等于 100 的文档,而不是查找每个商品的价格小于 100 的文档。

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

Mongo Playground蒙戈游乐场

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM