2

This code shows how I do it in Pymongo but what if I wanted to do that in RMongo?

from pymongo import MongoClient

connection = MongoClient()
db = connection.mydb
collection = db.transactions

pipe = [{'$group': {'_id': 'TRANS_AMNT_AVG', 'average': {'$avg':'$TRANS_AMOUNT'}}}]
result = collection.aggregate(pipeline=pipe)

print(list(result))

connection.close()

My data set is called transactions and the column is called TRANS_AMOUNT. I want to calculate the average TRANS_AMOUNT.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Dawid Stan
  • 21
  • 2

1 Answers1

1

I prefer to use mongolite for R to mongodb work, and in fact the code is very similar to that which you've supplied

library(mongolite)

mongo <- mongo(collection = "transaction", db = "test")

## dummy data
set.seed(2016)
df <- data.frame(TRANS_AMOUNT = rnorm(10,0,1))

## insert into mongo
mongo$insert(df)


## run the aggregation query
## note I've swapped single quotes for doubles, and vice versa
pipe = '[{"$group": {"_id": "TRANS_AMNT_AVG", "average": {"$avg":"$TRANS_AMOUNT"}}}]'

mongo$aggregate(pipeline = pipe)
# Imported 1 records. Simplifying into dataframe...
#              _id    average
# 1 TRANS_AMNT_AVG -0.3645931
SymbolixAU
  • 25,502
  • 4
  • 67
  • 139