要进行匹配,请在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") }
以下是在两个日期之间以特定值获取数据的查询。在这里,值1 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 }