[英]How do I perform an 'every' query in mongoose
Let's say I have a database with the a field of a document containing the following假设我有一个数据库,其中的文档字段包含以下内容
new Test({fruits: [ 'apple', 'orange', 'banana']})
I want to query the fruits array by another array, making sure that the array passed into the query contains every item in the fruit database.我想通过另一个数组查询水果数组,确保传递给查询的数组包含水果数据库中的每个项目。
In plain JavaScript I would do the following:在纯 JavaScript 中,我会执行以下操作:
var target = [ 'apple', 'orange', 'banana'];
var fruit2 = [ 'apple', 'orange', 'banana', 'peach']; // true
var fruit3 = [ 'mango', 'lemon', 'pineapple']; // false
var fruit4 = [ 'banana', 'apple', 'orange']; // true
const result = target.every(targetElem => fruit2.includes(targetElem));
console.log(result);
I can't use $in
because it goes through each item in the query array making sure all items exist.我不能使用
$in
因为它遍历查询数组中的每个项目,确保所有项目都存在。 In my case, I don't mind if the queried array contains extra items, as long as it has the same ones as the array in the database.就我而言,我不介意查询的数组是否包含额外的项目,只要它与数据库中的数组具有相同的项目即可。
If you are using MongodB version 3.6+, you could use $expr
with $map
, $allElementsTrue
, and $in
to evaluate each member of the array in each document against your query array.如果您使用的是 MongodB 3.6+ 版,则可以将
$expr
与$map
、 $allElementsTrue
和$in
以针对您的查询数组评估每个文档中数组的每个成员。
db.collection.find({
$expr:{
$allElementsTrue:{
$map:{
input: "$fruits",
in: {$in: ["$$this", [ 'apple', 'orange', 'banana', 'peach']]}
}
}
}
})
This will probably not be very efficient.这可能不是很有效。
Edit :编辑:
An alternate way to do this that could use an index, at least in part:这样做的另一种方法可以使用索引,至少部分:
db.collection.find({fruits:{$all:[ 'apple', 'orange', 'banana', 'peach']}})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.