描述
$elemMatch 數組查詢操作用于查詢數組值中至少有一個能完全匹配所有的查詢條件的文檔。語法格式如下:
{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }
如果只有一個查詢條件就沒必要使用 $elemMatch。
限制
- 不能指定 $where 查詢條件在 $elemMatch 內;
- 不能指定 $text 查詢條件在 $elemMatch 內;
實例
有如下測試數據:
{ _id: 1, results: [ 82, 85, 88 ] }
{ _id: 2, results: [ 75, 88, 89 ] }
如下語句用于匹配 results 數組中含有值同時滿足大于等于 80 且小于 85 的文檔。
db.scores.find({ results: { $elemMatch: { $gte: 80, $lt: 85 } } }
)
如下查詢結果,文檔中 results 中 82 滿足大于等于 80 且小于85。
{ "_id" : 1, "results" : [ 82, 85, 88 ] }
數組嵌套文檔
例如有如下測試數據:
{ _id: 1, results: [ { product: "abc", score: 10 }, { product: "xyz", score: 5 } ] }
{ _id: 2, results: [ { product: "abc", score: 8 }, { product: "xyz", score: 7 } ] }
{ _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 } ] }
如下語句用于匹配 results 數組中含有值同時滿足product 為 “xyz” 且 score 大于等于8 的文檔。
db.survey.find({ results: { $elemMatch: { product: "xyz", score: { $gte: 8 } } } }
)
查詢結果如下:
{ _id: 3, results: [ { product: "abc", score: 7 }, { product: "xyz", score: 8 } ] }
單查詢條件
如果只有單個查詢條件時沒有必要使用 $elemMatch 操作符。例如如下查詢:
// 沒有必要使用 $elemMatch 操作符
db.survey.find({ results: { $elemMatch: { product: "xyz" } } }
)
$elemMatch 操作符只有單個查詢條件,完全可以使用如下寫法代替:
db.survey.find({ "results.product": "xyz" }
)
官網文檔: https://docs.mongodb.com/manual/reference/operator/query/elemMatch/index.html
作者:學習園
來自個人博客: https://xuexiyuan.cn/article/detail/227.html