$unwind - Amazon DocumentDB

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

$unwind

$unwind 運算子用於從輸入文件解構陣列欄位,以輸出每個元素的文件。當您想要對陣列的個別元素執行操作,例如篩選、排序或轉換資料時,這會很有用。

參數

  • path:要復原的陣列欄位路徑。

  • includeArrayIndex:(選用) 指定要保留陣列元素索引的新欄位名稱。

  • preserveNullAndEmptyArrays:(選用) 決定當陣列欄位為 null 或空白陣列時,操作會保留原始文件。

範例 (MongoDB Shell)

下列範例示範如何使用 $unwind運算子解構陣列欄位,並對個別元素執行進一步的操作。

建立範例文件

db.people.insertMany([ { _id: 1, name: "jon", hobbies: ["painting", "dancing", "singing"] }, { _id: 2, name: "jane", hobbies: ["reading", "swimming"] }, { _id: 3, name: "jack", hobbies: [] } ])

查詢範例

db.people.aggregate([ { $unwind: "$hobbies" } ])

輸出

[ { _id: 1, name: 'jon', hobbies: 'painting' }, { _id: 1, name: 'jon', hobbies: 'dancing' }, { _id: 1, name: 'jon', hobbies: 'singing' }, { _id: 2, name: 'jane', hobbies: 'reading' }, { _id: 2, name: 'jane', hobbies: 'swimming' } ]

程式碼範例

若要檢視使用 $unwind命令的程式碼範例,請選擇您要使用的語言標籤:

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('people'); const result = await collection.aggregate([ { $unwind: '$hobbies' } ]).toArray(); console.log(result); 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['people'] result = list(collection.aggregate([ { '$unwind': '$hobbies' } ])) print(result) client.close() example()