Mongolite group by/aggregate on JSON object

nit*_*krs 2 json group-by aggregate mongodb mongolite

我的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"
Run Code Online (Sandbox Code Playgroud)

}

我需要在intent.intent字段上执行group,我正在使用Rstudio和mongolite库.我试过的是:

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

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

print(stats)
Run Code Online (Sandbox Code Playgroud)

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

  _id count
1  NA   727
Run Code Online (Sandbox Code Playgroud)

Ser*_*lan 5

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

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

结果:

{
    "_id" : "greeting",
    "count" : 1.0
}
Run Code Online (Sandbox Code Playgroud)