I am trying to execute this MongoDB command in Node.js:
db.events.group({
key: {
'timestamp.d': true
},
cond: {
'event_name': 'search'
},
initial: {
'count': 0,
'empty': 0,
'redos': 0
},
reduce: function(item, summaries) {
summaries.count++;
if (item.result_count == 0) {
summaries.empty++;
}
if (item.original_query) {
summaries.redos++;
}
var totalSuccesses = (summaries.count - summaries.redos - summaries.empty);
summaries.percentNonFailures = (totalSuccesses / summaries.count) * 100
}
})
This works great from the Mongo command like giving me summaries by day. When I try this in Node.js:
db.collection('events', function(err, collection) {
collection.group({
"timestamp.d": true
}, {
"event_name": "search"
}, {
count: 0,
empty: 0,
redos: 0,
percentNonFailure: 0,
}, function(item, summaries) {
sum开发者_StackOverflow中文版maries.count++;
if (item.result_count == 0) {
summaries.empty++;
}
if (item.original_query) {
summaries.redos++;
}
totalSuccesses = summaries.count - summaries.redos - summaries.empty
summaries.percentNonFailure = (totalSuccesses / summaries.count) * 100
}, function(err, results) {
self.eventEmitter.emit(doneEvent, results)
});
});
I get a single result with all the totals per day summed up together, so basically a sum of count, empty, redos for the entire period.
What is being done wrong in trying to convert the query to use in Node.js?
I had the same problem. I delved quite a bit through the mongodb driver code.
The problem is keys from sub documents. the driver ends up with something like
obj["timestamp.d"]
which is not what you want.
What I found is a 'command' argument that solved my problem.
db.collection('events', function(err, collection){
collection.group(
[ "timestamp.d" ], // array element, might also work the old way
{ "event_name": "search" },
{
count: 0,
empty: 0,
redos: 0,
percentNonFailure: 0,
},
function(item, summaries){
summaries.count++;
if (item.result_count == 0) { summaries.empty++; }
if (item.original_query) { summaries.redos++; }
totalSuccesses = summaries.count - summaries.redos - summaries.empty
summaries.percentNonFailure = (totalSuccesses / summaries.count) * 100
},
true, // use the group command
function(err, results){ self.eventEmitter.emit(doneEvent, results) }
);
})
You can see it here: collection.js from line 1054 on
I find it's difficult to to refer to Docs API. So I find some, and there they are:
Here is docs in MongoDB.
and Here is some more.
精彩评论