我想建议通过MongoDB documentation。
对于您的具体问题,请检查 $group 和 aggregation
A. 如果您的日期不随时间变化,那么您可以使用以下聚合:
db.getCollection('tests').aggregate([{
$group : {
_id : "$rcptdate",
"totalAmmount" : {
"$sum" : "$ammount"
}
}
}]);
输出:
/* 1 */
{
"_id" : ISODate("2018-10-24T00:00:00.000Z"),
"totalAmmount" : 3
}
/* 2 */
{
"_id" : ISODate("2018-10-23T10:00:00.000Z"),
"totalAmmount" : 10
}
B.如果您想要day of the month 的日期,请使用以下聚合:
db.getCollection('tests').aggregate([{
$group : {
_id : {
"day" : {"$dayOfMonth" : "$rcptdate"}
},
"totalAmmount" : {
"$sum" : "$ammount"
}
}
}])
输出:
/* 1 */
{
"_id" : {
"day" : 24
},
"totalAmmount" : 3
}
/* 2 */
{
"_id" : {
"day" : 23
},
"totalAmmount" : 16
}
以及,如何使用mongoose 库在 NodeJS 中实现。
let pipeline = [{
$group : {
_id : "$rcptdate",
"totalAmmount" : {
"$sum" : "$ammount"
}
}
}];
test1Model.aggregate(pipeline) // Get data from here
.allowDiskUse(true)
.exec(function(err, data) {
if(err || !data || !data[0]){
Logger.error("Error ");
} else{
let tempObj = data[0];
var test2 = new Test2Model(tempObj);
test2.save(function(error, data) { // Insert data to next DB
callback(error, data);
});
}
});