简体   繁体   English

查询Mongodb中的子文档数组

[英]Query an array of subdocuments in Mongodb

I have a collection of documents that goes like this:我有一个像这样的文档集合:

{
  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},   
  ]
},

I need to get all the documents that contains a distance in a given range.我需要获取包含给定范围内距离的所有文档。

Example: If I query for distance greater than 5000 and smaller than 9000 , I want to get documents "Whatever 1" and "Whatever 3"示例:如果我查询大于5000且小于9000距离,我想获得文档"Whatever 1""Whatever 3"

How can I do this?我怎样才能做到这一点?

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM