在 MongoDB 中提取两个日期之间且具有特定值的数据。分组并从中获取总值和计数?
要匹配,在 MongoDB 中使用 $match,要获取两个日期之间的数据,请使用 $gte 以及 $lte。让我们创建一个包含文档的集合 −
> db.demo560.insertOne({"value1":40,"value2":40,shippingDate:new ISODate("2020-02-26")});{ "acknowledged" : true, "insertedId" : ObjectId("5e8f3d5254b4472ed3e8e867") } > db.demo560.insertOne({"value1":20,"value2":60,shippingDate:new ISODate("2020-02-26")});{ "acknowledged" : true, "insertedId" : ObjectId("5e8f3d5254b4472ed3e8e868") } > db.demo560.insertOne({"value1":40,"value2":70,shippingDate:new ISODate("2020-03-31")});{ "acknowledged" : true, "insertedId" : ObjectId("5e8f3d5254b4472ed3e8e869") } > db.demo560.insertOne({"value1":40,"value2":130,shippingDate:new ISODate("2020-03-31")});{ "acknowledged" : true, "insertedId" : ObjectId("5e8f3d5254b4472ed3e8e86a") }
使用 find() 方法从集合中显示所有文档 −
> db.demo560.find();
这将产生以下输出 −
{ "_id" : ObjectId("5e8f3d5254b4472ed3e8e867"), "value1" : 40, "value2" : 40, "shippingDate" : ISODate("2020-02-26T00:00:00Z") } { "_id" : ObjectId("5e8f3d5254b4472ed3e8e868"), "value1" : 20, "value2" : 60, "shippingDate" : ISODate("2020-02-26T00:00:00Z") } { "_id" : ObjectId("5e8f3d5254b4472ed3e8e869"), "value1" : 40, "value2" : 70, "shippingDate" : ISODate("2020-03-31T00:00:00Z") } { "_id" : ObjectId("5e8f3d5254b4472ed3e8e86a"), "value1" : 40, "value2" : 130, "shippingDate" : ISODate("2020-03-31T00:00:00Z") }
以下是查询以获取两个日期之间并具有特定值的数据。这里,value1 40 是我们的特定值 −
> db.demo560.aggregate([ ... { ... $match: { ... "value1": 40, ... "shippingDate": { ... "$gte": ISODate("2020-02-26"), ... "$lte": ISODate("2020-03-31") ... } ... } ... }, ... { ... $group: { ... "_id": "$shippingDate", ... total: { ... $sum: '$value2' ... }, ... count: { ... $sum: 1 ... } ... } ... } ... ])
这将产生以下输出 −
{ "_id" : ISODate("2020-03-31T00:00:00Z"), "total" : 200, "count" : 2 } { "_id" : ISODate("2020-02-26T00:00:00Z"), "total" : 40, "count" : 1 }
广告