Mongo-Map simplifies query processing for a single document, but not for all records

I use the map framework to determine user statistics like this. trying to find lastOrderDate and totalOrders for each user.

db.order.mapReduce(function() { 
emit (this.customer,{count:1,orderDate:this.orderDate.interval_start}) },
function(key,values){  
    var sum =0 ; var lastOrderDate; 
values.forEach(function(value) {
  lastOrderDate=value['orderDate']; sum+=value['count'];  }); 
        return 
        {totalOrder:sum,lastOrderDate:lastOrderDate}; 
    },
  { 
query:{
status:"DELIVERED","customer":ObjectId("545f64e7e4b07a0a501276db")
},
  out:"order_total"}).find()

which gives me an absolutely correct result like this

{ "_id" : ObjectId("545f64e7e4b07a0a501276db"), 
"value" : { "totalOrder" : 21, "lastOrderDate" : ISODate("2015-10-02T18:30:00Z") } }

but when I use the same query for all users, I just removed the client filter from the query

                  "customer":ObjectId("545f64e7e4b07a0a501276db")}

now when i run the query again it shows the wrong and weird output like this

{ "_id" : ObjectId("5443765ae4b05294c8944d5b"), "value" : { "count" : 1, "orderDate" : ISODate("2014-10-18T18:30:00Z") } }
{ "_id" : ObjectId("54561911e4b07a0a501276af"), "value" : { "totalOrder" : 2, "lastOrderDate" : ISODate("2015-03-14T18:30:00Z") } }
{ "_id" : ObjectId("54561b9ce4b07a0a501276b1"), "value" : { "totalOrder" : NaN, "lastOrderDate" : null } }
{ "_id" : ObjectId("5458712ee4b07a0a501276c2"), "value" : { "totalOrder" : 2, "lastOrderDate" : ISODate("2014-11-03T18:30:00Z") } }
  // check this user
  { "_id" : ObjectId("545f64e7e4b07a0a501276db"), "value" : { "totalOrder" : NaN, "lastOrderDate" : null } }
  //
{ "_id" : ObjectId("54690771e4b0070527c657ed"), "value" : { "totalOrder" : NaN, "lastOrderDate" : ISODate("2015-11-02T18:30:00Z") } }
{ "_id" : ObjectId("54696c64e4b07f3c07010b4a"), "value" : { "totalOrder" : 2, "lastOrderDate" : ISODate("2015-11-15T18:30:00Z") } }
{ "_id" : ObjectId("546980d1e4b07f3c07010b4d"), "value" : { "totalOrder" : 4, "lastOrderDate" : ISODate("2015-03-24T18:30:00Z") } }
{ "_id" : ObjectId("54699ac4e4b07f3c07010b51"), "value" : { "totalOrder" : NaN, "lastOrderDate" : null } }
{ "_id" : ObjectId("54699d0be4b07f3c07010b55"), "value" : { "totalOrder" : NaN, "lastOrderDate" : null } }

As you can see now, it shows different output for one user who

{ "_id" : ObjectId("545f64e7e4b07a0a501276db"), 
"value" : { "totalOrder" : NaN, "lastOrderDate" : null } }   

I'm a newbie to collapse the map in mongo, help!

+4
source share

Source: https://habr.com/ru/post/1628897/


All Articles