MongoDB +合并词典

时间:2017-07-06 14:28:41

标签: mongodb aggregation-framework

我有一个数据库,构造为

{p, q} = {0, 0}

现在我进行搜索

library(forecast)

omega <- USJudgeRatings[,1]

tbats(y                = omega,
      use.box.cox      = TRUE,
      use.trend        = TRUE,
      use.damped.trend = TRUE,
      use.arma.errors  = TRUE,
      start.p = 3,
      start.q = 2,
      trace = TRUE)
# 
#  ARIMA(3,0,2) with non-zero mean : Inf
#  ARIMA(0,0,0) with non-zero mean : -55.63664
#  ARIMA(1,0,0) with non-zero mean : -53.50348
#  ARIMA(0,0,1) with non-zero mean : -53.47905
#  ARIMA(0,0,0) with zero mean     : -57.75828
#  ARIMA(1,0,1) with non-zero mean : -51.19495
# 
#  Best model: ARIMA(0,0,0) with zero mean     
# 
# BATS(0, {0,0}, 0.979, -)
# 
# Call: tbats(y = omega, use.box.cox = TRUE, use.trend = TRUE, use.damped.trend = TRUE, 
#     use.arma.errors = TRUE, start.p = 3, start.q = 2, trace = TRUE)
# 
# Parameters
#   Lambda: 0
#   Alpha: -0.04239053
#   Beta: 0.04362955
#   Damping Parameter: 0.978616
# 
# Seed States:
#          [,1]
# [1,] 1.917976
# [2,] 0.017468
# 
# Sigma: 0.1206409
# AIC: 163.774

现在我想将每个键的所有值加到一个结果中,如:

{"id":5,

 "type":{"hello":1,"sad":2,"luck":1}})

有没有一种方法可以实现这一点,提前谢谢。

1 个答案:

答案 0 :(得分:1)

Mongo 3.4.4版本

您可以使用$objectToArray创建一组键值对。

db.collection.aggregate({
    "$project": {
        "type": {
            "$objectToArray": "$type"
        }
    }
}, {
    "$unwind": "$type"
}, {
    "$group": {
        "_id": "$type.k",
        "count": {
            "$sum": "$type.v"
        }
    }
})

旧版本

您可以使用mapreduce

var map = function() {
   var type = this.type;
   Object.keys(type).forEach( function(key) { emit( key, type[key] ); } );
};

var reduce = function( key, values ) {
   return values.length;
};

db.collection.mapReduce( map, reduce, { out: { "inline" : 1}  } )['results']