如何基于Mongodb的doc字段中的每个数组项过滤集合 [英] How to filter a collection based on each array item in a doc field in Mongodb

查看:50
本文介绍了如何基于Mongodb的doc字段中的每个数组项过滤集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个收藏,就像这样:

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

我需要写什么查询,以便数组 parts 中的每个项目大于等于输入数组 [1,5]中具有相同数组索引的项目?

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]?

输出为:

[
{ "_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}}

蒙戈游乐场

或使用下面的JS代码构建更通用的内容:

or use below JS code to build something more generic:

let input = [1,5];
let query = Object.fromEntries(input.map((val, i) => ([ "parts." + i, { $gte: val } ])));

console.log(query);

这篇关于如何基于Mongodb的doc字段中的每个数组项过滤集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆