如何在MongoDB中查找数组大小在一定范围内的文档? [英] How to find a document with array size within a range in MongoDB?
问题描述
给出以下文档结构:
{
_id : Mongo ID,
data : [someData1, someData2, ..., someDataN]
}
我想获取所有data
大小在a
和b
之间的文档(严格的正整数,请考虑a < b
始终为true).
我首先想到使用 $size
,但是Mongo文档指出:
I want to get all documents which data
size is between a
and b
(strict positive integers, consider a < b
is always true).
I first thought about using $size
, but the Mongo doc states:
$size
不接受值的范围.要根据元素数量不同的字段选择文档,请创建一个计数器字段,在将元素添加到字段时会增加该字段.
$size
does not accept ranges of values. To select documents based on fields with different numbers of elements, create a counter field that you increment when you add elements to a field.
(强调我的)
如何在不使用计数器的情况下检索长度在a
和b
之间的data
数组的所有文档?
How to retrieve all the documents with a data
array of length between a
and b
without using a counter?
相关但未解决:
- 此答案建议使用计数器
- 此问题,询问如何查询内部长度 得到很多答案
- 此答案,建议使用:
{ 'data.' + b : { $exists : true } }
,但我不知道它的可靠性以及如何将其应用于范围 - 此问题有关如何查找具有最小数组长度的文档
- This answer which suggests using a counter
- This question which asks how to query an internal length and got many answers
- This answer which suggests to use:
{ 'data.' + b : { $exists : true } }
but I don't know how reliable it is and how it could apply to a range - This question about how to find documents with a minimal array length
推荐答案
您可以使用$exists
运算符方法,在查询中包括多个术语并以编程方式进行构建:
You can use the $exists
operator approach by including multiple terms in your query and building it up programmatically:
var startKey = 'data.' + (a-1);
var endKey = 'data.' + b;
var query = {};
query[startKey] = {$exists: true};
query[endKey] = {$exists: false};
db.test.find(query);
例如,对于a=1
和b=3
,您最终得到的query
对象看起来像:
So for a=1
and b=3
, for example, you end up with a query
object that looks like:
{
"data.0" : {
"$exists" : true
},
"data.3" : {
"$exists" : false
}
}
第一部分确保至少有a
个元素,第二部分确保不超过b
个元素.
The first part ensures there are at least a
elements, and the second part ensures there are no more than b
elements.
这篇关于如何在MongoDB中查找数组大小在一定范围内的文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!