2012-11-27 77 views
2

我試圖創建一個MongoDB的集合類似於組​​查詢:集團在rmongodb

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做一組查詢成功?

回答

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 s tatement」

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