$isArray - Amazon DocumentDB

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

$isArray

Amazon DocumentDB 中的$isArray运算符用于检查文档中的字段是否为数组。此运算符在聚合管道和条件表达式中可用于处理数组类型字段。

参数

  • field:用于检查它是否为数组的字段路径。

示例(MongoDB 外壳)

此示例演示如何使用$isArray运算符来识别 “清单” 字段为数组的文档。

创建示例文档

db.videos.insertMany([ { "_id":1, "name":"Live Soft", "inventory": {"Des Moines": 1000, "Ames" : 500}}, { "_id":2, "name":"Top Pilot", "inventory": {"Mason City": 250, "Des Moines": 1000}}, { "_id":3, "name":"Romancing the Rock", "inventory": {"Mason City": 250, "Ames" : 500}}, { "_id":4, "name":"Bravemind", "inventory": [{"location": "Mason City", "count": 250}, {"location": "Des Moines", "count": 1000}, {"location": "Ames", "count": 500}]} ]);

查询示例

db.videos.aggregate([ { $match: { $isArray: "$inventory" } }, { $project: { _id: 1, name: 1, "inventory.location": 1, "inventory.count": 1 } } ]).pretty();

输出

{ "_id": 4, "name": "Bravemind", "inventory": [ { "location": "Mason City", "count": 250 }, { "location": "Des Moines", "count": 1000 }, { "location": "Ames", "count": 500 } ] }

代码示例

要查看使用该$isArray命令的代码示例,请选择要使用的语言的选项卡:

Node.js
const { MongoClient } = require('mongodb'); async function run() { 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 collection = db.collection('videos'); const result = await collection.aggregate([ { $match: { $isArray: '$inventory' } }, { $project: { _id: 1, name: 1, "inventory.location": 1, "inventory.count": 1 } } ]).toArray(); console.log(result); await client.close(); } run();
Python
from pymongo import MongoClient client = MongoClient('mongodb://<username>:<password>@<cluster-endpoint>:27017/?tls=true&tlsCAFile=global-bundle.pem&replicaSet=rs0&readPreference=secondaryPreferred&retryWrites=false') db = client['test'] collection = db['videos'] result = list(collection.aggregate([ { '$match': { '$isArray': '$inventory' } }, { '$project': { '_id': 1, 'name': 1, 'inventory.location': 1, 'inventory.count': 1 } } ])) print(result) client.close()