2016-11-03 16 views
0

如何通过mogoDB线司机做到这一点:如何通过mongodb-wire-protocol(OP_QUERY)做db.collection.aggregate()?

db.collection.aggregate(
    [ 
     { $match: <query condition> }, 
     { $group: { _id: null, count: { $sum: 1 } } } 
    ] 
) 

特别是如何建立的查询字符串?

我需要这样做的原因是:为避免在分片文件存在的情况下计数会导致计数不准确的分片群,我们必须使用db.collection.aggregate()方法的$ group阶段来$文档。

回答

1

当谈到使用有线协议时,驱动程序提供的包装器方法可能会显得非常不利于协议。例如,db.collection.aggregate(): https://docs.mongodb.com/manual/reference/method/db.collection.aggregate/

但是当你看看总dbcmd下,它给你更多的线索: https://docs.mongodb.com/manual/reference/command/aggregate/#dbcmd.aggregate

因此,举例来说,如果你有一个有线协议驱动程序实现OP_QUERY,然后与具有与另一个字段,其称为DOC_ITEMS项目的阵列的字段DOC_NAME含有收集COLL_name文档的数据库DB_NAME,可以执行聚合查询如下面的伪协议:

OP_QUERY - DB=DB_name, COLL=$cmd 
#skip=0 
#return=1 
query:{ 
    "aggregate": "COLL_name", 
    "pipeline": [ 
     { 
     "$project": { 
      "n_items": { 
       "$size": "$DOC_ITEMS" 
      }, 
      "DOC_NAME": 1 
     } 
    } 
    ] 
} 
fields:{ 
} 

如果库提供重要价值的对象和数组“放”操作,查询构建通过以下步骤:

Pipeline = new Array(); 
ProjectionItems = new Object(); 

Size = new Object(); 
Size.Put ("$size", "$DOC_ITEMS"); 

//calculated field 
ProjectionItems.Put ("n_items", Size);    

//include "DOC_NAME" field in result projection 
ProjectionItems.Put ("DOC_NAME", 1);    

Projection_PipelineCmd = new Object(); 
Projection_PipelineCmd.Put ("$project", ProjectionItems); 

//add the projection definition to the pipeline array 
Pipeline.Put (Projection_PipelineCmd); 

Query = new Object(); 
Query.Put ("aggregate", "COLL_name"); 
Query.Put ("pipeline", Pipeline); 

希望这点你在正确的方向!