如何通过mongodb-wire-protocol(OP_QUERY)做db.collection.aggregate()?

时间:2016-11-03 21:41:22

标签: mongodb mongodb-query

我如何通过mogoDB线驱动器执行此操作:

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

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

我需要这样做是因为:为了避免在分片群集中,如果存在孤立文档,则计数可能导致计数不准确,我们必须使用db.collection.aggregate()方法的$ group阶段来对文档求和。

1 个答案:

答案 0 :(得分: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的有线协议驱动程序,那么对于包含集合COLL_name的数据库DB_name,其中包含一个字段DOC_NAME,另一个字段是一个名为DOC_ITEMS的项目数组,您可以执行聚合查询,如作为下面的伪协议:

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:{
}

如果您的库为对象和数组提供键值“Put”操作,则查询将通过以下过程构建:

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);

希望这能指出你正确的方向!