本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
$slice
$slice 投影運算子會限制查詢結果中傳回的陣列元素數目。它可讓您從陣列欄位的開頭或結尾擷取特定數量的元素,而無需載入整個陣列。
參數
範例 (MongoDB Shell)
下列範例示範如何使用$slice投影運算子,只傳回陣列欄位中的前兩個項目。
建立範例文件
db.inventory.insertMany([
{ _id: 1, item: "notebook", tags: ["office", "school", "supplies", "writing"] },
{ _id: 2, item: "pen", tags: ["office", "writing"] },
{ _id: 3, item: "folder", tags: ["office", "supplies", "storage", "organization"] }
]);
查詢範例
db.inventory.find(
{},
{ item: 1, tags: { $slice: 2 } }
)
輸出
{ "_id" : 1, "item" : "notebook", "tags" : [ "office", "school" ] }
{ "_id" : 2, "item" : "pen", "tags" : [ "office", "writing" ] }
{ "_id" : 3, "item" : "folder", "tags" : [ "office", "supplies" ] }
程式碼範例
若要檢視使用$slice投影運算子的程式碼範例,請選擇您要使用的語言標籤:
- 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('inventory');
const result = await collection.find(
{},
{ projection: { item: 1, tags: { $slice: 2 } } }
).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['inventory']
result = list(collection.find(
{},
{'item': 1, 'tags': {'$slice': 2}}
))
print(result)
client.close()
example()