2

我正在尝试在 MongoDB 集合上创建一个组查询,类似于:

db.orders.group( {
    key: { ord_dt: 1, 'item.sku': 1 },
    cond: { ord_dt: { $gt: new Date( '01/01/2012' ) } },
    reduce: function ( curr, result ) { },
    initial: { }
} )

我正在使用 rmongodb。通过查看 rmongodb 包文档,他们使用mongo.command来运行计数命令:

mongo <- mongo.create() 
if (mongo.is.connected(mongo)) {
    buf <- mongo.bson.buffer.create() 
    mongo.bson.buffer.append(buf, "count", "people") 
    mongo.bson.buffer.append(buf, "query", mongo.bson.empty()) 
    command <- mongo.bson.from.buffer(buf) 
    result = mongo.command(mongo, "test", command) 
    if (!is.null(result)) {  
        iter = mongo.bson.find(result, "n") print(mongo.bson.iterator.value(iter)) 
    }
}

也不同:

mongo.distinct <- function(mongo, db, collection, key) {    
    b <- mongo.command(mongo, db, list(distinct=collection, key=key))    
    if(!is.null(b))
        b <- mongo.bson.value(b, "values")
    }
names <- mongo.distinct(mongo, "test", "people", "name")

有没有人成功使用mongo.command过进行组查询?

4

1 回答 1

0

这是使用聚合框架的简单“GROUP BY 语句”的基本示例。请注意,这需要 MongoDB 2.1 或更高版本: http: //docs.mongodb.org/manual/core/aggregation/

首先建立连接和一些虚拟数据:

library(rmongodb)
mongo <- mongo.create()

db <- "stackoverflow"
coll <- "grpmong"
ns <- paste(db, coll, sep = ".")

mongo.insert(mongo, ns, mongo.bson.from.list(list(y=1, x=1)))
mongo.insert(mongo, ns, mongo.bson.from.list(list(y=1, x=2)))
mongo.insert(mongo, ns, mongo.bson.from.list(list(y=2, x=3)))
mongo.insert(mongo, ns, mongo.bson.from.list(list(y=2, x=4)))

检查数据格式:

 >mongo.find.one(mongo, ns, mongo.bson.empty())
    _id : 7          51e002b881620de5fe2973ec
    y : 1    1.000000
    x : 1    1.000000

以下将产生等价于:

SELECT y '_id', SUM(x) total
FROM grpmong
GROUP BY y

创建“GROUP BY 语句”

x <- list('$group' = list('_id' = '$y',
                          'total' = list('$sum' = '$x')
                          ))
grpBSON <- mongo.bson.from.list(x) 

创建聚合管道并将“GROUP BY 语句”添加到其中:

buf <- mongo.bson.buffer.create();
mongo.bson.buffer.append(buf, "aggregate", coll); 
  mongo.bson.buffer.start.array(buf, "pipeline");
    mongo.bson.buffer.append(buf, "0", grpBSON);
  mongo.bson.buffer.finish.object(buf);
cmd <- mongo.bson.from.buffer(buf);

运行命令:

res <- mongo.command(mongo, db, cmd)

检查结果:

> print(res)
result : 4
  0 : 3
    _id : 1 2.000000
    total : 1 7.000000
  1 : 3
    _id : 1 1.000000
    total : 1 3.000000
  ok : 1 1.000000
于 2013-07-12T13:41:32.643 回答