【问题标题】:Group/count by part of a field按字段的一部分分组/计数
【发布时间】:2014-04-13 11:27:56
【问题描述】:

我有这样的收藏

{"foo" : "abc-123", more fields.... }
{"foo" : "abc-456", more fields.... }
{"foo" : "cde-000", more fields.... }
{"foo" : "cde-555", more fields.... }
{"foo" : "else-9991234", more fields.... }

想按foo的第一部分分组计数:

{
    "abc": 2,
    "cde": 2,
    "else": 1
}

我考虑过为此使用聚合框架,但我不确定如何提取第一部分:

myColl.aggregate([
     $project: { firstPart: { ???? '$foo' 

【问题讨论】:

    标签: javascript mongodb mapreduce aggregation-framework


    【解决方案1】:

    很遗憾您需要像这样拆分,否则您可能会在聚合管道中使用 $substr 运算符。

    但既然你需要这个功能,你可以使用 mapReduce:

    db.collection.mapReduce() {
        function() {
            var parts = this.foo.split("-");
            emit( parts[0], 1 );
        },
        function(key,values){
            return values.length;
        },
        { "out": { "inline": 1 } }
    )
    

    任何发送到reducer的东西都会计算数组中的“值”,任何只有一个键的东西都会绕过reducer,但我们已经返回了1。

    【讨论】:

      【解决方案2】:

      我不确定这是否可能与 mongo 相关。最终,您必须按第一部分拆分字符串和组。

      如果我是你,我宁愿修改你的架构以添加新字段foo1,这将是字符串的第一部分。你可以用foreach来做到这一点

      db.collection.find().forEach(function(el){
        // here split your el['foo'] and update the el with new `foo1` which will have your first part
      })
      

      之后,您可以轻松使用聚合框架。

      【讨论】:

      • 谢谢!您认为可以使用 map-reduce 代替 AF 吗?在我的工作流程中添加新字段会很复杂...
      猜你喜欢
      • 1970-01-01
      • 2021-01-27
      • 1970-01-01
      • 1970-01-01
      • 2020-05-13
      • 1970-01-01
      • 1970-01-01
      • 2020-05-26
      • 2014-11-05
      相关资源
      最近更新 更多