我有一个像这样的文档集合:
{
name: "Whatever 1".
distances: [
{name: "first distance", distance: 3000},
{name: "another distance", distance: 8000},
]
},
{
name: "Whatever 2".
distances: []
},
{
name: "Whatever 3".
distances: [
{name: null, distance: 6000},
]
},
{
name: "Whatever 4".
distances: [
{name: "hello", distance: 100000},
]
},
我需要获取所有包含给定范围内距离的文档。
示例:如果查询的距离大于5000
且小于9000
,我想获取文档"Whatever 1"
和"Whatever 3"
我该怎么做?
答案 0 :(得分:1)
您可以使用$elemMatch为distances
数组的单个子文档指定范围条件:
db.col.find({ distances: { $elemMatch: { distance: { $gt: 5000, $lt: 9000 } } } })