mongolite - correct syntax for aggregate method

♀尐吖头ヾ 提交于 2019-12-24 01:09:17

问题


Data

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)

Question

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

Mongo Shell query

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

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

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


Attempt

I thought

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

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

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


回答1:


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


来源:https://stackoverflow.com/questions/34271799/mongolite-correct-syntax-for-aggregate-method

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!