我正在接近MongoDB,并且我有一个具有以下结构的数据库:
{ "_id" : 14185, "ranges" : [ { "first" : 17, "last" : 19 }, { "first" : 6, "last" : 9 } ] }
{ "_id" : 16478, "ranges" : [ { "first" : 26, "last" : 30 }, { "first" : 3, "last" : 5 } , { "first" : 3, "last" : 5 } ] }
{ "_id" : 17896, "ranges" : [ { "first" : 124, "last" : 130 }, { "first" : 140, "last" : 146 } ] }
因此,我总是拥有一个"ranges"
数组,其中包含许多文档:每个文档都有一个"first"
和"last"
值。
给出一个值,例如29
,我想编写一个查询,给我类似的信息
{ "_id" : 16478, "ranges" : [ { "first" : 26, "last" : 30 } ] }
有可能吗?
答案 0 :(得分:0)
您应将问题$ projection与$ elemMatch一起使用,如下所示:
db.collection.find({'ranges.first': {$lt: 29} ,'ranges.last': {$gt: 29} },{ ranges: { $elemMatch: {first: {$lt: 29} ,last: {$gt: 29} } }}).lean();