Nối mảng trong MongoDB với $concatArrays
Để nối các mảng trong MongoDB, chúng ta sử dụng toán tử $concatArrays trong pipeline aggregation.
1. Tạo collection và chèn dữ liệu
> db.demo435.insertOne({ "FirstName": ["Chris"], "LastName": ["Brown"] });
{ "acknowledged": true, "insertedId": ObjectId("5e7719b1bbc41e36cc3cae97") }
> db.demo435.insertOne({ "FirstName": ["David"], "LastName": ["Miller"] });
{ "acknowledged": true, "insertedId": ObjectId("5e7719bdbbc41e36cc3cae98") }
> db.demo435.insertOne({ "FirstName": ["John"], "LastName": ["Doe"] });
{ "acknowledged": true, "insertedId": ObjectId("5e7719c6bbc41e36cc3cae99") }
2. Xem dữ liệu gốc
> db.demo435.find().pretty();
Kết quả:
{
"_id": ObjectId("5e7719b1bbc41e36cc3cae97"),
"FirstName": ["Chris"],
"LastName": ["Brown"]
}
{
"_id": ObjectId("5e7719bdbbc41e36cc3cae98"),
"FirstName": ["David"],
"LastName": ["Miller"]
}
{
"_id": ObjectId("5e7719c6bbc41e36cc3cae99"),
"FirstName": ["John"],
"LastName": ["Doe"]
}
3. Truy vấn nối mảng
> db.demo435.aggregate([
{
$project: {
FullName: { $concatArrays: ["$FirstName", "$LastName"] }
}
}
])
4. Kết quả
{ "_id": ObjectId("5e7719b1bbc41e36cc3cae97"), "FullName": ["Chris", "Brown"] }
{ "_id": ObjectId("5e7719bdbbc41e36cc3cae98"), "FullName": ["David", "Miller"] }
{ "_id": ObjectId("5e7719c6bbc41e36cc3cae99"), "FullName": ["John", "Doe"] }
Lưu ý
$concatArrays chỉ hoạt động trong aggregation pipeline. Nếu cần cập nhật tài liệu, hãy kết hợp với $merge hoặc sử dụng updateOne với $set.