$elemMatch - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$elemMatch

Amazon DocumentDB 中的$elemMatch運算子用於查詢陣列欄位,並傳回陣列中至少有一個元素符合指定條件的文件。當您具有具有巢狀陣列或內嵌文件的複雜資料結構時,此運算子特別有用。

規劃器 2.0 版已新增 的索引支援。 $elemMatch

參數

  • field:要查詢的陣列欄位。

  • query:比對陣列元素的條件。

 

$all表達式$elemMatch內使用

在$all表達式$elemMatch內使用 如需在$all表達式中使用$elemMatch運算子的限制,請參閱 。

範例 (MongoDB Shell)

下列範例示範如何使用 $elemMatch運算子來尋找parts陣列至少有一個符合指定條件的元素的文件。

建立範例文件

db.col.insertMany([ { _id: 1, parts: [{ part: "xyz", qty: 10 }, { part: "abc", qty: 20 }] }, { _id: 2, parts: [{ part: "xyz", qty: 5 }, { part: "abc", qty: 10 }] }, { _id: 3, parts: [{ part: "xyz", qty: 15 }, { part: "abc", qty: 100 }] }, { _id: 4, parts: [{ part: "abc", qty: 150 }] } ]);

查詢範例

db.col.find({ parts: { "$elemMatch": { part: "xyz", qty: { $lt: 11 } } } })

輸出

{ "_id" : 1, "parts" : [ { "part" : "xyz", "qty" : 10 }, { "part" : "abc", "qty" : 20 } ] } { "_id" : 2, "parts" : [ { "part" : "xyz", "qty" : 5 }, { "part" : "abc", "qty" : 10 } ] }

程式碼範例

若要檢視使用 $elemMatch命令的程式碼範例,請選擇您要使用的語言標籤:

Node.js
const { MongoClient } = require('mongodb'); async function example() { const client = await MongoClient.connect('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false'); const db = client.db('test'); const col = db.collection('col'); const result = await col.find({ parts: { "$elemMatch": { part: "xyz", qty: { $lt: 11 } } } }).toArray(); console.log(JSON.stringify(result, null, 2)); await client.close(); } example();
Python
from pymongo import MongoClient def example(): client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] col = db['col'] result = list(col.find({ 'parts': { '$elemMatch': {'part': 'xyz', 'qty': {'$lt': 11}} } })) print(result) client.close() example()