我如何总结我的mongodb集合中的值?
我有一个mongoose
模型,看起来类似于这样的:
var TestSchema = new Schema({ test_username: {type: String, required: true}, test_content: {type: String}, reactions: [{ test_username: {type: String, required: true}, value: {type: Number, required: true}, sent_at: {type: Date, required: true, default: Date.now} }], created_at: {type: Date, default: Date.now}, updated_at: {type: Date, default: Date.now} })
它存储我的Test
对象有很多反应。 每个反应包含1
或-1
value
和不同的用户名。 现在我正在尝试创build一个端点来获取Test
id作为input,并返回它包含的所有反应的总和。
我开始写它:
testRoutes.get('/:id/reactions/', functions.validateRequestsGET, function(req, res){ var testId = req.params.id; var query = Test... //here I'm stuck query.exec(function(err, reactions){ if(err) { res.send(err); return; } res.json(reactions); }); });
你能给我提示如何创build一个查询,可以返回一个JSON的总金额? 像{reactions: 17}
或类似的东西?
尝试这个:
Test.aggregate( { $match: { _id: testId // you might want to convert this from string to ObjectId() }}, { $project: { sumReactions: { $sum: "$reactions.value" } }} )
看一下在文档中的组累加器$组 ,也是很好的例子。
- 在两个不同的字段mongodb + node.js中search值
- 相当于Node.js中的mongo shell db.collection.runCommand()
- MongoDB正则expression式search – 从使用JavaScript驱动程序和NodeJS开始
- 仅将数据返回到数组中
- 在mongodb / node中存储敏感数据
- Mongodb – TypeError:ReplSetServers不是一个函数
- 用mongoose进行build筑投票的“正确方法”?
- 使用Node.JS,MongoDB和Socket.IO的实时多人游戏:游戏循环和asynchronous调用
- Mongooseasynchronous调用内循环与asynchronous库