[英]How to filter a collection based on each array item in a doc field in Mongodb
Let's say I have a collection, like so:假设我有一个集合,如下所示:
[
{ "_id": "101", parts: [1.2, 2] },
{ "_id": "102", parts: [2, 3.5] },
{ "_id": "103", parts: [4.1, 10] }
]
What is the query I need to write so that each item in the array parts
is greater than equal to the item with the same array index in an input array [1, 5]
?我需要编写什么查询,以便数组
parts
中的每个项目都大于等于输入数组[1, 5]
中具有相同数组索引的项目?
output would be:输出将是:
[
{ "_id": "103", parts: [4.1, 10] } // 4.1 >= 1 and 10 >= 5
]
is this possible?这可能吗? any idea?
任何的想法?
You can use the dot notation and run following query for your example:您可以使用点符号并为您的示例运行以下查询:
{"parts.0":{"$gte":1},"parts.1":{"$gte":5}}
or use below JS code to build something more generic:或者使用下面的 JS 代码来构建更通用的东西:
let input = [1,5]; let query = Object.fromEntries(input.map((val, i) => ([ "parts." + i, { $gte: val } ]))); console.log(query);
If you know the input array before query then you can create query object from it first then pass this object to the query:如果您在查询之前知道输入数组,那么您可以先从它创建查询对象,然后将此对象传递给查询:
let query = input.reduce((acc, cur, index) => {
acc['parts.' + index] = { $gt: cur };
return acc;
}, {});
// [1, 5] will create {"parts.0": {$gt: 1},"parts.1": {$gt: 5}}
db.collection.find(query)...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.