问题
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