mongodb mongo db 查询大于和小于的数组值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10069910/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:35:52  来源:igfitidea点击:

mongo db querying array values with greater and less than

arraysmongodb

提问by Rishabh

I have a schema similar to

我有一个类似于

{
   'user_id' : 1,
   'marks' : [10, 40]
}

I want to find the number of users who have scored marks between 20 and 30 at least once.

我想找到至少一次得分在 20 到 30 之间的用户数量。

I tried the following query

我尝试了以下查询

db.users.count({
   'marks' : {$gte: '20', $lt: '30'}
})

But this also included those with marks more than 30 ...

但这也包括那些分数超过30的人......

采纳答案by Geoff

So assuming you had the following data in collection scores:

因此,假设您在收集分数中有以下数据:

{ 'user_id' : 1, 'marks' : [ 10, 40 ] }
{ 'user_id' : 2, 'marks' : [ 5, 18 ] }
{ 'user_id' : 3, 'marks' : [ 15, 25 ] }
{ 'user_id' : 4, 'marks' : [ 22, 33 ] }

Then you would expect to filter user_ids 3 and 4, a count of 2.

然后您会期望过滤 user_ids 3 和 4,计数为 2。

The simplest way to run your query is to do:

运行查询的最简单方法是:

db.scores.count({'marks':{$in: [20,21,22,23,24,25,26,27,28,29,30]}})

But not pretty...

不过不好看...

回答by JohnnyHK

Use $elemMatchto constrain both parts of the range query to the samemarkselement:

用于$elemMatch将范围查询的两个部分限制为同一marks元素:

db.users.count({
    marks: {$elemMatch: {$gte: 20, $lt: 30}}
})

回答by cantdutchthis

Isn't it just this:

不就是这样吗:

db.scores.count( { 'marks' : { '$gt' : min_value , '$lt' : max_value } } )

Which in your case would translate to:

在您的情况下,这将转化为:

db.scores.count( { 'marks' : { '$gt' : 20 , '$lt' : 30 } } )

回答by Enjoy

db.scores.count(
   { marks: { $elemMatch: { $gte: 20, $lt: 30} } }
)

For more information refer https://docs.mongodb.com/manual/reference/operator/query/elemMatch/

有关更多信息,请参阅https://docs.mongodb.com/manual/reference/operator/query/elemMatch/