MongoDB 数组类型查询 —— $elemMatch 操作符
生活随笔
收集整理的這篇文章主要介紹了
MongoDB 数组类型查询 —— $elemMatch 操作符
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
描述
$elemMatch 數組查詢操作用于查詢數組值中至少有一個能完全匹配所有的查詢條件的文檔。語法格式如下:
{ <field>: { $elemMatch: { <query1>, <query2>, ... } } }如果只有一個查詢條件就沒必要使用 $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
總結
以上是生活随笔為你收集整理的MongoDB 数组类型查询 —— $elemMatch 操作符的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 海信VIDAA MAX激光影院如何,在商
- 下一篇: NYOJ 44 子串和