问题
I have mongo documents:
{
id:1
time:[
1,
2,
10
]
}
{
id:2
time:[
1,
4,
8,
10
]
}
I want find all documents, which have time between 3 and 5 or between 7 or 9 (document with id 2). I dont know how do this.
I try:
mongo.find( $or : [{time:{$gte:3, $lte:5}}, {time:{$gte:7, $lte:9}}] )
and mongo returns documents with id 1 and 2, but i need id2 with time[4, 8].
How to apply a condition to each element of the array, but NOT to entire array?
p.s. Size array "time" maybe different
回答1:
Try using the $elemMatch operator:
mongo.find({time:{$elemMatch: {$gte:3,$lte:5}}})
Like with:
mongo.find(
{
$or: [
{time:{$elemMatch: {$gte:3,$lte:5}}},
{time:{$elemMatch: {$gte:7,$lte:9}}}
]
}
)
回答2:
If you're using the 'time' array as a placeholder for another array of storage then the previous comment with elemMatch should help you as this should cope with other numerical searches such as exam scores.
However, if you are using it for processing dates / times etc. then you might be better of working with unix timestamps for storage as this is done via integers and quite easy to search and store in mongodb and support is easy to come by for the majority of programming languages out there. (example in php: mktime() and DateTime::getTimestamp()).
来源:https://stackoverflow.com/questions/17990948/find-in-array-between-dates-in-mongo