Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> MongoDB

จะนับและรวมฟิลด์ระหว่างวันที่ 2 วันใน MongoDB ได้อย่างไร


ใช้การรวม $gte และ $lte พร้อมกับ $sum เพื่อนับและรวมฟิลด์ระหว่างวันที่ 2 วัน ให้เราสร้างคอลเลกชันที่มีเอกสารก่อน -

> db.countandsumdemo.insertOne({"Value":10,"created_at":ISODate('2019-10-11')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e038e6df5e889d7a51994fa")
}
> db.countandsumdemo.insertOne({"Value":50,"created_at":ISODate('2019-01-31')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e038e77f5e889d7a51994fb")
}
> db.countandsumdemo.insertOne({"Value":100,"created_at":ISODate('2019-06-31')});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5e038e8af5e889d7a51994fc")
}

ต่อไปนี้เป็นแบบสอบถามเพื่อแสดงเอกสารทั้งหมดจากคอลเลกชันโดยใช้วิธี find() -

> db.countandsumdemo.find().pretty();

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

{
   "_id" : ObjectId("5e038e6df5e889d7a51994fa"),
   "Value" : 10,
   "created_at" : ISODate("2019-10-11T00:00:00Z")
}
{
   "_id" : ObjectId("5e038e77f5e889d7a51994fb"),
   "Value" : 50,
   "created_at" : ISODate("2019-01-31T00:00:00Z")
}
{
   "_id" : ObjectId("5e038e8af5e889d7a51994fc"),
   "Value" : 100,
   "created_at" : ISODate("2019-07-01T00:00:00Z")
}

ต่อไปนี้เป็นแบบสอบถามเพื่อนับและรวมเขตข้อมูลระหว่างวันที่ 2 -

> db.countandsumdemo.aggregate(
...    [{
...       $match: {
...          created_at: {
...             $gte: new Date('2019-05-01'),
...             $lte: new Date('2019-12-31')
...          }
...       }
...    }, {
... $group: {
...    _id: null,
...    SUM: {
...       $sum: "$Value"
...    },
...    COUNT: {
...       $sum: 1
...    }
... }
... }]
... );

สิ่งนี้จะสร้างผลลัพธ์ต่อไปนี้ -

{ "_id" : null, "SUM" : 110, "COUNT" : 2 }