Hãy để chúng tôi tạo một bộ sưu tập với các tài liệu -
> db.demo677.insertOne({Value:10});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea421f404263e90dac943f8")
}
> db.demo677.insertOne({Value:50});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea421f704263e90dac943f9")
}
> db.demo677.insertOne({Value:20});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea421fa04263e90dac943fa")
}
> db.demo677.insertOne({Value:20});
{
"acknowledged" : true,
"insertedId" : ObjectId("5ea421fe04263e90dac943fb")
} 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.demo677.find();
Điều này sẽ tạo ra kết quả sau -
{ "_id" : ObjectId("5ea421f404263e90dac943f8"), "Value" : 10 }
{ "_id" : ObjectId("5ea421f704263e90dac943f9"), "Value" : 50 }
{ "_id" : ObjectId("5ea421fa04263e90dac943fa"), "Value" : 20 }
{ "_id" : ObjectId("5ea421fe04263e90dac943fb"), "Value" : 20 } Sau đây là truy vấn để thêm các giá trị của một trường cụ thể -
> db.demo677.aggregate({ $group: { _id : null, sum : { $sum: "$Value" } } }); Điều này sẽ tạo ra kết quả sau -
{ "_id" : null, "sum" : 100 }