简体   繁体   English

如何根据Mongodb中doc字段中的每个数组项过滤集合

[英]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}}

Mongo Playground蒙戈游乐场

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.

相关问题 MONGODB-将集合中的字段添加到Item数组中的字段 - MONGODB - adding a field in collection to a field in Item array 如何基于MongoDB中的另一个集合嵌入字段值更新嵌入集合字段的数组? - How to update array of embedded collection field based on another collection embedded field value in MongoDB? 如果字段数组和参数数组相交,则过滤MongoDb集合 - Filter MongoDb collection if field array and argument array intersect MongoDB - 聚合 - 过滤集合中数组字段中的最后一个元素 - MongoDB - Aggregate - Filter on the last element in an array field in collection 如何在MongoDb集合的数组字段中投影元素? - How to projection element in array field of MongoDb collection? Mongodb根据字段是否包含数组值作为子字符串来查询集合 - Mongodb query a collection based on if the field contains an array value as substring 如何根据数组元素向 mongoDB 集合的文档添加新字段 - How to add a new field to mongoDB collection's documents based on an array element 根据每个数组项的第一个整数过滤Javascript数组 - Filter Javascript array based on first integer of each array item C# MongoDB 查询:根据数组的最后一项进行过滤 - C# MongoDB query: filter based on the last item of array 如何过滤Mongodb中的集合 - How to filter a collection in Mongodb
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM