日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

MongoDB 数组类型查询 —— $elemMatch 操作符

發布時間:2023/12/1 编程问答 47 豆豆
生活随笔 收集整理的這篇文章主要介紹了 MongoDB 数组类型查询 —— $elemMatch 操作符 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

描述

$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

    總結

    以上是生活随笔為你收集整理的MongoDB 数组类型查询 —— $elemMatch 操作符的全部內容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。