【问题标题】:Query an array of subdocuments in Mongodb在 Mongodb 中查询子文档数组
【发布时间】:2019-08-01 04:22:58
【问题描述】:

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

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

我该怎么做?

【问题讨论】:

    标签: mongodb mongoose mongodb-query


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2016-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-11
      • 1970-01-01
      • 1970-01-01
      • 2017-01-04
      相关资源
      最近更新 更多