Để nối (concatenate) các phần tử mảng số nguyên thành chuỗi, dùng $reduce lặp qua mảng và $concat ghép chuỗi trong aggregation.
Tạo collection:
> db.demo377.insertOne({"ListOfIds":[1001,1002,1003,1004,1005,1006,1007]});
{ "acknowledged" : true, "insertedId" : ObjectId("5e5a73462ae06a1609a00b0e") }
Xem dữ liệu:
> db.demo377.find().pretty();
{ "_id" : ObjectId("5e5a73462ae06a1609a00b0e"), "ListOfIds" : [ 1001, 1002, 1003, 1004, 1005, 1006, 1007 ] }
Aggregation nối mảng với dấu "++":
> db.demo377.aggregate([
{ "$project": {
"ListOfIds": {
"$let": {
"vars": {
"key": {
"$reduce": {
"input": "$ListOfIds",
"initialValue": "",
"in": { "$concat": ["$$value", "++", { "$toLower": "$$this" }] }
}
}
},
"in": { "$substrCP": ["$$key", 2, { "$strLenCP": "$$key" }] }
}
}
}}
])
Kết quả:
{ "_id" : ObjectId("5e5a73462ae06a1609a00b0e"), "ListOfIds" : "1001++1002++1003++1004++1005++1006++1007" }
Giải thích:
$reduce: duyệt mảng, gom chuỗi.initialValue: ""khởi tạo chuỗi rỗng$concat: nối chuỗi.$$valuelà tích lũy,$$thislà phần tử hiện tại$toLower: chuyển số thành chuỗi (số tự động cast)$let+$substrCP: cắt bỏ "++" đầu tiên (vị trí 0,1)
MongoDB 4.4+ đơn giản hơn: Dùng $reduce với $concat trực tiếp, hoặc $join (nếu có).