Để nối các chuỗi từ hai trường vào một trường thứ ba, bạn có thể sử dụng cú pháp sau
db.yourCollectionName.aggregate(
[
{ $project: { "yourNewFieldName": { $concat: [ "$yourFieldName1", " yourDellimiterValue ", "$yourFieldName2" ] } } }
]
); Trước tiên, hãy để chúng tôi tạo một bộ sưu tập với các tài liệu
>db.concatenateStringsDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Doe"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9bb7362d66697741252444")
}
>db.concatenateStringsDemo.insertOne({"StudentFirstName":"John","StudentLastName":"Smith"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9bb7402d66697741252445")
}
>db.concatenateStringsDemo.insertOne({"StudentFirstName":"Carol","StudentLastName":"Taylor"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9bb74c2d66697741252446")
}
>db.concatenateStringsDemo.insertOne({"StudentFirstName":"David","StudentLastName":"Miller"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9bb7752d66697741252447")
}
>db.concatenateStringsDemo.insertOne({"StudentFirstName":"James","StudentLastName":"Williams"});
{
"acknowledged" : true,
"insertedId" : ObjectId("5c9bb7862d66697741252448")
} Sau đây là truy vấn để hiển thị tất cả các tài liệu từ một bộ sưu tập với sự trợ giúp của phương thức find ()
> db.concatenateStringsDemo.find().pretty();
Điều này sẽ tạo ra kết quả sau
{
"_id" : ObjectId("5c9bb7362d66697741252444"),
"StudentFirstName" : "John",
"StudentLastName" : "Doe"
}
{
"_id" : ObjectId("5c9bb7402d66697741252445"),
"StudentFirstName" : "John",
"StudentLastName" : "Smith"
}
{
"_id" : ObjectId("5c9bb74c2d66697741252446"),
"StudentFirstName" : "Carol",
"StudentLastName" : "Taylor"
}
{
"_id" : ObjectId("5c9bb7752d66697741252447"),
"StudentFirstName" : "David",
"StudentLastName" : "Miller"
}
{
"_id" : ObjectId("5c9bb7862d66697741252448"),
"StudentFirstName" : "James",
"StudentLastName" : "Williams"
} Sau đây là truy vấn để nối các chuỗi từ hai trường vào một trường thứ ba. Chúng tôi đang nối các trường “StudentFirstName” và “StudentLastName” ở đây thành một trường thứ ba
> db.concatenateStringsDemo.aggregate(
... [
... { $project: { "StudentFullName": { $concat: [ "$StudentFirstName", " / ", "$StudentLastName" ] } } }
... ]
... ); Điều này sẽ tạo ra kết quả sau
{ "_id" : ObjectId("5c9bb7362d66697741252444"), "StudentFullName" : "John / Doe" }
{ "_id" : ObjectId("5c9bb7402d66697741252445"), "StudentFullName" : "John / Smith" }
{ "_id" : ObjectId("5c9bb74c2d66697741252446"), "StudentFullName" : "Carol / Taylor" }
{ "_id" : ObjectId("5c9bb7752d66697741252447"), "StudentFullName" : "David / Miller" }
{ "_id" : ObjectId("5c9bb7862d66697741252448"), "StudentFullName" : "James / Williams" }