查询Mongodb中的子文档数组

时间:2019-03-10 20:14:59

标签: mongodb mongoose mongodb-query

我有一个像这样的文档集合:

{
  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"

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您可以使用$elemMatchdistances数组的单个子文档指定范围条件:

db.col.find({ distances: { $elemMatch: { distance: { $gt: 5000, $lt: 9000 } } } })