Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅
中国的 Amazon Web Services 服务入门
(PDF)。
本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。
$size
$size查询运算符匹配数组字段具有精确指定数量的元素的文档。这对于根据数组长度筛选文档很有用。
参数
-
field:要检查的数组字段。
-
count:数组必须包含的元素的确切数量。
示例(MongoDB 外壳)
以下示例演示如何使用$size运算符查找恰好具有三个标签的所有产品。
创建示例文档
db.products.insertMany([
{ _id: 1, name: "Laptop", tags: ["electronics", "computers", "portable"] },
{ _id: 2, name: "Mouse", tags: ["electronics", "accessories"] },
{ _id: 3, name: "Desk", tags: ["furniture", "office", "workspace"] },
{ _id: 4, name: "Monitor", tags: ["electronics"] }
]);
查询示例
db.products.find({ tags: { $size: 3 } });
输出
{ "_id" : 1, "name" : "Laptop", "tags" : [ "electronics", "computers", "portable" ] }
{ "_id" : 3, "name" : "Desk", "tags" : [ "furniture", "office", "workspace" ] }
代码示例
要查看使用$size查询运算符的代码示例,请选择要使用的语言对应的选项卡:
- 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 collection = db.collection('products');
const result = await collection.find({ tags: { $size: 3 } }).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']
collection = db['products']
result = list(collection.find({'tags': {'$size': 3}}))
print(result)
client.close()
example()