簡體   English   中英

查詢Mongodb中的子文檔數組

[英]Query an array of subdocuments in Mongodb

我有一個像這樣的文檔集合:

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

我怎樣才能做到這一點?

您可以使用$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