How to calculate the average of particular column using RMongo?

228 Views Asked by At

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.

1

There are 1 best solutions below

0
SymbolixAU On

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