我需要获取集合中某个值的出现次数,如下所示:
System.out.println(position+ " "+ key.getSpName()+ " "+ key.getReaderDesc());
我想要返回的水线find()参数:
09-28 20:23:47.731 20156-20156/com.blah.blah I/System.out﹕ 0 Company1 Front door
09-28 20:23:47.745 20156-20156/com.blah.blah I/System.out﹕ 1 Company1 Back Door
09-28 20:23:47.745 20156-20156/com.blah.blah I/System.out﹕ 2 Occipitech Front door
09-28 20:23:47.746 20156-20156/com.blah.blah I/System.out﹕ 3 Occipitech Garage door
到目前为止,我能够获得除了计数之外的一切,其中包含:
[
{author: 'Diego', name: 'This is a great post', date:'03/13/78'},
{author: 'Raul', name: 'Recipe for success', date:'02/03/99'},
{author: 'Diego', name: 'Having too much fun', date:'01/01/77'},
{author: 'Diego', name: 'Another post by me', date:'10/9/99'},
{author: 'Diego', name: 'Mi first post', date:'01/01/73'},
{author: 'Mariano', name: 'Mi best post', date:'01/01/95'},
]
我尝试过使用“sum:['1']”,但这只会给我一个名为“1”的属性,每个结果行的值为0。
答案 0 :(得分:0)
使用node.js mongo DB native的聚合方法 documentation
我的代码示例: 从餐厅ID = ...的GROUP顺序中选择计数在ISO DATE前10个字符 - 天(2015-01-10)
if(restaurantsFound.length > 0) {
var result = [],
Q = require('q'),
promises = [];
for(var r in restaurantsFound) {
promises[r] = (function () {
var deferred = Q.defer();
Order.native(function(err, collection) {
if (err) {
console.error(err);
deferred.reject(err);
}
var ObjectID = require('mongodb').ObjectID;
var restaurantId = new ObjectID(restaurantsFound[r]);
collection.aggregate([
{ $match : {
restaurant : restaurantId
}},
{ $group : {
_id : {"_id":{"$substr":["$createdAt", 0, 10]}},
count : { $sum : 1 },
restaurant: {$addToSet: "$restaurant"}
}}
], function(err, result) {
deferred.resolve(result);
});
});
return deferred.promise;
})();
}
Q
.allSettled(promises)
.then(function(data) {
var result = [];
for(var k in data) {
result[k] = [];
for(var l in data[k].value) {
result[k].push({
restaurant: data[k].value[l].restaurant[0].toString(),
count: data[k].value[l].count,
date: data[k].value[l]._id._id
});
}
}
return res.ok(result);
}).catch(function(error) {
console.error(error.message);
return res.badRequest({message: error.message});
});
}