Để thêm một trường mới, hãy sử dụng $ addFields trong MongoDB. Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.demo719.insertOne(
... {
... "Number":"7374644",
... "details" : {
... "otherDetails" : [
... {
... "ProductId" :"102",
... "ProductPrice" : NumberInt(500)
... },
... {
... "ProductId" :"103",
... "ProductPrice" : NumberInt(2000)
... }
... ]
... }
... }
... );
{
"acknowledged" : true,
"insertedId" : ObjectId("5eaae56c43417811278f5882")
} 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.demo719.find();
Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5eaae56c43417811278f5882"), "Number" : "7374644", "details" : { "otherDetails" : [ { "ProductId" : "102", "ProductPrice" : 500 }, { "ProductId" : "103", "ProductPrice" : 2000 } ] } } Sau đây là truy vấn để thêm một trường mới và nối kết quả giá chia cho một số cụ thể trong đó -
> db.demo719.aggregate([
... {
... $addFields:{
... productPriceList: {
... $reduce: {
... input: {
... $map: {
... input: "$details.otherDetails.ProductPrice",
... in: { $toString: { $divide: ["$$this", 5] } }
... }
... },
... initialValue: "",
... in: { $concat: ["$$value", "$$this", " \n "] }
... }
... }
... }
... },
... {
... $project: {
... _id: 0,
... Number:1,
... productPriceList:1
... }
... }
... ]) Điều này sẽ tạo ra kết quả sau -
{ "Number" : "7374644", "productPriceList" : "100 \n 400 \n " }