Mongodb是否可以聚合对象?

编程入门 行业动态 更新时间:2024-10-26 06:39:03
本文介绍了Mongodb是否可以聚合对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试汇总此文档中的数据包总数.

I am trying to aggregate the total sum of packets in this document.

{ "_id" : ObjectId("51a6cd102769c63e65061bda"), "capture" : "1369885967", "packets" : { "0" : "595", "1" : "596", "2" : "595", "3" : "595", ... } }

我能找到的最接近的是

db.collection.aggregate({ $match: { capture : "1369885967" } }, {$group: { _id:null, sum: {$sum:"$packets"}}});

但是它返回总和0,这显然是错误的.

However it returns sum 0, which is obviously wrong.

{ "result" : [ { "_id" : null, "sum" : 0 } ], "ok" : 1 }

如何获取所有数据包的总和?

How do I get the sum of all the packets?

推荐答案

由于您将值保存在对象而不是数组中,因此需要使用mapReduce.

Since you have the values in an object instead of an array, you'll need to use mapReduce.

// Emit the values as integers var mapFunction = function() { for (key in this.packets) { emit(null, parseInt(this.packets[key])); } } // Reduce to a simple sum var reduceFunction = function(key, values) { return Array.sum(values); } > db.collection.mapReduce(mapFunction, reduceFunction, {out: {inline:1}}) { "results" : [ { "_id" : null, "value" : 2381 } ], "ok" : 1, }

如果可能的话,应该将值作为数字类型的数组发出,因为这会给您更多选择(即聚合),并且(除非数据集很大)可能会带来性能上的好处.

If at all possible, you should emit the values as an array of a numeric type instead since that gives you more options (ie aggregation) and (unless the data set is large) probably performance benefits.

更多推荐

Mongodb是否可以聚合对象?

本文发布于:2023-11-22 13:00:58,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1617509.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   Mongodb

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!