$elemMatch - Amazon DocumentDB

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

$elemMatch

Amazon DocumentDB 中的$elemMatch运算符用于查询数组字段,并返回数组中至少有一个元素符合指定条件的文档。当您拥有包含嵌套数组或嵌入式文档的复杂数据结构时,此运算符特别有用。

Planner 版本 2.0 添加了对索引的支持$elemMatch

参数

  • field:要查询的数组字段。

  • query:与数组元素匹配的标准。

 

$all表达式$elemMatch中使用

有关在$all表达式中使用$elemMatch运算符的限制,请参阅在 $all 表达式中使用 $elemMatch

示例(MongoDB 外壳)

以下示例演示如何使用$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()