简体   繁体   中英

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"

How can I do this?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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