2

这段代码展示了我是如何在 Pymongo 中做到这一点的,但是如果我想在 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()

我的数据集被称为transactions,列被称为TRANS_AMOUNT。我想计算平均值TRANS_AMOUNT

4

1 回答 1

1

我更喜欢将mongoliteR 用于 mongodb 工作,实际上代码与您提供的代码非常相似

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
于 2016-12-06T01:51:45.540 回答