【问题标题】:how to aggregate the sum of the jsonarray sizes in Collection in MongoDB?如何在 MongoDB 的 Collection 中聚合 jsonarray 大小的总和?
【发布时间】:2018-01-27 04:55:29
【问题描述】:

我在 MongoDB 中有集合,集合中的每个文档都在下面的表单中

{ "记录":"A", “样本”:[ “一个”, “乙”, “C”] } { “记录”:“B”, “样本”:[ "s", "t", “你”, "v", “w”] }

请帮助查询可以在 mongodb 中执行以获取整个集合中的样本总数

在本例中:3+5 = 8

【问题讨论】:

标签: mongodb


【解决方案1】:

在您的文档“样本”中的一个数组中,因此您首先需要使用$unwind 来解构元素。

db.collection.aggregate([ 
    { $unwind : "$samples" },
    { $group : { _id : "sample", count: {$sum:1} }}
])

输出:

{
    "_id" : "sample",
    "count" : 8.0
}

【讨论】:

    猜你喜欢
    • 2018-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-01
    • 1970-01-01
    • 2012-06-20
    • 2014-09-11
    • 2018-06-02
    相关资源
    最近更新 更多