Dùng hàm aggregate để cập nhật trường dùng giá trị trường khác. Tạo 2 collection: name và studentInformation.
Collection name:
> db.name.insert({"FirstName":"John","LastName":"Smith"});
WriteResult({ "nInserted" : 1 })
Collection studentInformation:
> db.studentInformation.insert({"StudentFirstName":"Carol","StudentLastName":"Taylor"});
WriteResult({ "nInserted" : 1 })
Cập nhật collection name từ studentInformation (nối FirstName + LastName thành FullName):
> db.studentInformation.aggregate( [ { "$addFields":{ "FullName":{ "$concat":["$StudentFirstName"," ","$StudentLastName"] } } }, { "$out":"name" } ] );
Kiểm tra collection name:
> db.name.find().pretty();
Kết quả:
{ "_id" : ObjectId("5c6c013068174aae23f5ef56"), "StudentFirstName" : "Carol", "StudentLastName" : "Taylor", "FullName" : "Carol Taylor" }