【问题标题】:Mongolite group by/aggregate on JSON objectMongolite 对 JSON 对象进行分组/聚合
【发布时间】:2018-03-19 03:03:57
【问题描述】:

我的 mongodb 集合中有一个这样的 json 文档: 更新文件:

{
"_id" : ObjectId("59da4aef8c5d757027a5a614"),
"input" : "hi",
"output" : "Hi. How can I help you?",
"intent" : "[{\"intent\":\"greeting\",\"confidence\":0.8154089450836182}]",
"entities" : "[]",
"context" : "{\"conversation_id\":\"48181e58-dd51-405a-bb00-c875c01afa0a\",\"system\":{\"dialog_stack\":[{\"dialog_node\":\"root\"}],\"dialog_turn_counter\":1,\"dialog_request_counter\":1,\"_node_output_map\":{\"node_5_1505291032665\":[0]},\"branch_exited\":true,\"branch_exited_reason\":\"completed\"}}",
"user_id" : "50001",
"time_in" : ISODate("2017-10-08T15:57:32.000Z"),
"time_out" : ISODate("2017-10-08T15:57:35.000Z"),
"reaction" : "1"

}

我需要在 intent.intent 字段上执行分组,并且我正在使用带有 mongolite 库的 Rstudio。 我试过的是:

pp = '[{"$unwind": "$intent"},{"$group":{"_id":"$intent.intent", "count": {"$sum":1} }}]'

stats <- chat$aggregate(
      pipeline=pp,
      options = '{"allowDiskUse":true}'
    )

print(stats)

但它不起作用,上面代码的输出是

  _id count
1  NA   727

【问题讨论】:

  • 我对示例 json 文档运行您的聚合查询并得到 { "_id" : "greeting", "count" : 1.0 } 有什么问题?
  • 但是我没有得到这个输出。如前所述,我正在使用 Rstudio,但我仍然遇到问题。你能告诉我你在哪里试过这段代码吗?
  • 我刚刚用 robomongo 试过你的代码
  • 感谢您到目前为止的帮助,您是对的,此查询正在处理我提供的文档,但这只是真实文档的子集。我已经更新了问题中的真实文档......并且聚合不起作用......
  • 问题,intent 属性值是字符串而不是对象,需要将行转换为"intent" : [{"intent":"greeting","confidence":0.8154089450836182}],

标签: json mongodb group-by aggregate mongolite


【解决方案1】:

如果意图属性类型是字符串并将对象保持为字符串。 我们可以使用\" 将其拆分为数组,并使用数组的第三项。

db.getCollection('test1').aggregate([
{ "$project": { intent_text : { $arrayElemAt : [ { $split: ["$intent", "\""] } ,3  ] } } },
{ "$group": {"_id": "$intent_text" , "count": {"$sum":1} }}
])

结果:

{
    "_id" : "greeting",
    "count" : 1.0
}

【讨论】:

    猜你喜欢
    • 2017-02-14
    • 1970-01-01
    • 1970-01-01
    • 2014-05-22
    • 2020-11-09
    • 2020-02-26
    • 2021-06-26
    • 2019-10-31
    • 1970-01-01
    相关资源
    最近更新 更多