mongolite-聚合方法的正确语法 [英] mongolite - correct syntax for aggregate method

查看:144
本文介绍了mongolite-聚合方法的正确语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

数据

在这里,我正在使用mongolite将虚拟数据插入到测试mongodb数据库中:

Here I'm using mongolite to insert dummy data into a test mongodb database:

library(mongolite)

## create dummy data
df <- data.frame(id = c(1,2,3,4),
                 region = c("r1", "r1", "r2", "r2"))

> df
  id region
1  1     r1
2  2     r1
3  3     r2
4  4     r2

## insert into database
mong <- mongo(collection = "test", db = "test", url = "mongodb://localhost")
mong$insert(df)

问题

如何使用aggregate方法查找每个区域的记录数?

How do I find the number of records for each region using the aggregate method?

Mongo Shell查询

在mongo shell中运行时,此查询返回正确答案

This query returns the correct answer when run in the mongo shell

db.test.aggregate({ $group : { _id : "$region", number_records : { $sum : 1}}})

现在如何将其转换为mongolite的正确语法?

How do I now translate this into the correct syntax for mongolite?

尝试

我以为

mong$aggregate('{ $group : { _id : "$region", number_records : { $sum : 1}}}')

会这样做,但出现Error: invalid JSON object错误.

would do it, but I get an Error: invalid JSON object error.

我觉得自己已经忽略了一些非常简单的东西!

I get the feeling I've overlooked something really simple!

推荐答案

仔细查看

Looking closer at the documentation (page 4), it shows I actually need quotes around each key/value, and square brackets around the whole query:

> mong$aggregate('[{ "$group" : 
                      { "_id" : "$region", 
                        "number_records" : { "$sum" : 1}
                      }
                  }]')
 Imported 2 records. Simplifying into dataframe...
  _id number_records
1  r2              2
2  r1              2

这篇关于mongolite-聚合方法的正确语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆