$concatArrays - Amazon DocumentDB

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

$concatArrays

Amazon DocumentDB $concatArrays 中的彙總運算子用於將兩個或多個陣列串連至單一陣列。當您需要將多個資料陣列合併為單一陣列以進行進一步處理或分析時,這會很有用。

參數

  • array1:要串連的第一個陣列。

  • array2:要串連的第二個陣列。

  • [array3, ...]:(選用) 要串連的其他陣列。

範例 (MongoDB Shell)

下列範例示範如何使用 $concatArrays運算子將兩個陣列合併為單一陣列。

建立範例文件

db.collection.insertMany([ { "_id": 1, "name": "John Doe", "hobbies": ["reading", "swimming"], "skills": ["programming", "design"] }, { "_id": 2, "name": "Jane Smith", "hobbies": ["hiking", "cooking"], "skills": ["marketing", "analysis"] } ]);

查詢範例

db.collection.aggregate([ { $project: { _id: 0, name: 1, all_activities: { $concatArrays: ["$hobbies", "$skills"] } } } ]);

輸出

[ { "name": "John Doe", "all_activities": [ "reading", "swimming", "programming", "design" ] }, { "name": "Jane Smith", "all_activities": [ "hiking", "cooking", "marketing", "analysis" ] } ]

程式碼範例

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

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('mydb'); const collection = db.collection('mycollection'); const result = await collection.aggregate([ { $project: { _id: 0, name: 1, all_activities: { $concatArrays: ['$hobbies', '$skills'] } } } ]).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['mydb'] collection = db['mycollection'] result = list(collection.aggregate([ { '$project': { '_id': 0, 'name': 1, 'all_activities': { '$concatArrays': ['$hobbies', '$skills'] } } } ])) print(result) client.close() example()