ใช้ $reduce ร่วม $concat และ $let เพื่อวนลูปรวมค่าในอาร์เรย์เป็นสตริงเดียว
ตัวอย่างข้อมูลทดสอบ
> db.demo377.insertOne({"ListOfIds":[1001,1002,1003,1004,1005,1006,1007]});
แสดงข้อมูล
> db.demo377.find().pretty();
{
"_id" : ObjectId("5e5a73462ae06a1609a00b0e"),
"ListOfIds" : [ 1001, 1002, 1003, 1004, 1005, 1006, 1007 ]
}
คำสั่ง Aggregation รวมอาร์เรย์ด้วย ++
> db.demo377.aggregate([
{ "$project": {
"ListOfIds": {
"$let": {
"vars": {
"key": {
"$reduce": {
"input": "$ListOfIds",
"initialValue": "",
"in": { "$concat": ["$$value", "++", { "$toLower": "$$this" }] }
}
}
},
"in": { "$substrCP": ["$$key", 2, { "$strLenCP": "$$key" }] }
}
}
}}
])
ผลลัพธ์
{
"_id" : ObjectId("5e5a73462ae06a1609a00b0e"),
"ListOfIds" : "1001++1002++1003++1004++1005++1006++1007"
}
คำอธิบาย:
$reduceวนลูปสะสมสตริง เริ่มจาก "" แล้ว concat "++" + ค่าปัจจุบัน- ได้สตริงขึ้นต้น "++" (เช่น "++1001++1002...")
$substrCPตัด "++" นำหน้าออก (เริ่มที่ index 2, ความยาว = ความยาวสตริงทั้งหมด)
MongoDB 4.4+: ใช้ $reduce แบบง่ายกว่าหรือ $function สำหรับ logic ซับซ้อน