猫鼬对所有文档求和一个值 [英] mongoose sum a value across all documents
本文介绍了猫鼬对所有文档求和一个值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望计算与我的查询匹配的文档中具有名称数量的所有列,
ticket.count({time: {$gte: a}, time: {$lte: today}}).then(function (numTickets) {
如何获取文档列金额的总结果?
例如,如果我有:
{ 时间:20,数量:40}{ 时间:40,数量:20}
它会返回总金额(60)?
请记住,我确实需要在查询中使用 {time: {$gte: a}, time: {$lte: today}
.
我该怎么做?
解决方案
尝试使用
I am looking to count all columns with the name amount in the documents that match my query,
tickets.count({time: {$gte: a}, time: {$lte: tomorrow}}).then(function (numTickets) {
How can I get the total result of the document column called amount?
Example, if I do have:
{ time: 20, amount: 40}
{ time: 40, amount: 20}
it would return the total amount(60)?
Remember that I do need to use {time: {$gte: a}, time: {$lte: tomorrow}
in the query.
How would I do this?
解决方案
Try it with the aggregation framework using the $match and $group operators, i.e. something like this
db.tickets.aggregate([
{ $match: { time: {$gte: a, $lte: tomorrow} } },
{ $group: { _id: null, amount: { $sum: "$amount" } } }
])
for example with test data like this
/* 1 */
{
"_id" : ObjectId("57e0ed40828913a99c2ceb46"),
"time" : 20,
"amount" : 40
}
/* 2 */
{
"_id" : ObjectId("57e0ed40828913a99c2ceb47"),
"time" : 40,
"amount" : 20
}
/* 3 */
{
"_id" : ObjectId("57e0ed40828913a99c2ceb48"),
"time" : 50,
"amount" : 10
}
/* 4 */
{
"_id" : ObjectId("57e0ed40828913a99c2ceb49"),
"time" : 10,
"amount" : 5
}
a pipeline (with dummy time range) like the following
db.tickets.aggregate([
{ $match: { time: {$gte: 20, $lte: 40} } },
{ $group: { _id: null, amount: { $sum: "$amount" } } }
])
would give you a result like this
/* 1 */
{
"_id" : null,
"amount" : 60
}
这篇关于猫鼬对所有文档求和一个值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文