[英]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"
我怎樣才能做到這一點?
您可以使用$elemMatch為distances
數組的單個子文檔指定范圍條件:
db.col.find({ distances: { $elemMatch: { distance: { $gt: 5000, $lt: 9000 } } } })
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.