本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$size
$size 查詢運算子會比對陣列欄位具有指定數量元素的文件。這適用於根據陣列長度篩選文件。
參數
-
field:要檢查的陣列欄位。
-
count:陣列必須包含的確切元素數量。
範例 (MongoDB Shell)
以下範例示範如何使用 $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()