Vorausgesetzt Sie haben eine Verkaufssammlung mit Dokumenten
{ "_id": ObjectId("579d91a4e474b2af2f1ddc65"), "date": ISODate("2015-06-29T22:00:00Z"), "quantity": 1, "price": 30 }
{ "_id": ObjectId("579d9193e474b2af2f1ddc66"), "date": ISODate("2015-07-28T22:00:00Z"), "quantity": 3, "price": 20 }
{ "_id": ObjectId("579d91a4e474b2af2f1ddc67"), "date": ISODate("2015-08-29T22:00:00Z"), "quantity": 2, "price": 10 }
{ "_id": ObjectId("579d91a4e474b2af2f1ddc68"), "date": ISODate("2015-09-29T22:00:00Z"), "quantity": 4, "price": 15 }
{ "_id": ObjectId("579d919ee474b2af2f1ddc69"), "date": ISODate("2015-11-28T22:00:00Z"), "quantity": 2, "price": 20 }
Mit Karten reduzieren die Lösung
var mapFunc = function() {
date = this.date;
if (new ISODate("2015-06-01T00:00:00Z") <= date && date <= new ISODate("2016-01-01T00:00:00Z")) {
var totalPrice = this.quantity * this.price;
if (new ISODate("2015-11-01T00:00:00Z") <= date) emit ("lastMonth", totalPrice);
if (new ISODate("2015-09-01T00:00:00Z") <= date) emit ("lastQuarter", totalPrice);
emit("lastSemester", totalPrice);
}
}
var reduceFunc = function(key, values) {
return Array.sum(values);
}
db.sales.mapReduce(mapFunc, reduceFunc, { out: { inline : 1 } });
Die Ergebnisse sind
"results" : [ { "_id" : "lastSemester", "value" : 210 },
{ "_id" : "lastMonth", "value" : 40 },
{ "_id" : "lastQuarter", "value" : 100 } ]
Obwohl
sein, ich weiß nicht (und möchte) wissen, wie man es mit Aggregation für diese bestimmte Sammlung erreichen kann.
Das einzige, was, was in den Sinn kommt, ist zu $group
Monat
db.corders.aggregate(
{ $match: { $and: [ { date: { $gte: new ISODate("2015-06-01T00:00:00Z") } }, { date : { $lte: new ISODate("2016-01-01T00:00:00Z") } } ] } },
{ $group: { "_id": { "$month": "$date" }, totalPrice: { $sum: { $multiply: [ "$price", "$quantity" ] } } } });
, die die Ergebnisse
{ "_id" : 11, "totalPrice" : 40 }
{ "_id" : 9, "totalPrice" : 60 }
{ "_id" : 8, "totalPrice" : 20 }
{ "_id" : 7, "totalPrice" : 60 }
{ "_id" : 6, "totalPrice" : 30 }
gibt, die lokal weiter verarbeitet werden soll, entsprechend der Aufgabe.
Danke, das hat den Zweifel geklärt. –
Danke für die Bereitstellung von Aggregation-Framework-Lösung. – tarashypka