2017-06-13 203 views
0

我想将mongoDB查询转换为Javacode,但它在mongo中返回适当的值,但是当在java代码中运行时,它不会返回count的合适值(它正在返回适当的machineID,errorID但计数为空,而不是计数应返回记录数)。MongoDB聚合查询到java代码

蒙戈驱动程序名称

mongo-java-driver-3.3.0.jar 

MongoDB的查询

db.getCollection('collectionName').aggregate([ 
    {"$match" : {"machineID": {"$in": ["1","10"]} , "errorID" : "error5"}}, 
    {"$group" : {_id : {machineID : "$machineID", errorID : "$errorID"}, count : {$sum : 1} } }, 
    {$project : {machineID : "$_id.machineID", errorID : "$_id.errorID", count : "$count", _id : 0}} 
]) 

Javacode:

AggregateIterable<Document> resultset =dbCollection.aggregate(Arrays.asList(
       new Document("$group", new Document("_id", new BasicDBObject("machineID", "$machineID").append("errorID","$errorID").append("count", new BasicDBObject("$sum",1)))), 
       new Document("$project", new Document("machineID", "$_id.machineID").append("errorID", "$_id.errorID").append("count", "$count").append("_id", 0)))); 

返回值

machine ID -> 100 
errorID -> error3 
count -> null 
+0

是否有东西,你相信没有解决您的问题提供答案吗?如果是这样,请评论答案以澄清究竟需要解决的问题。如果它确实回答了你问的问题,那么请注意[接受你的答案](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work)给你的问题问。 –

回答

2

它可以帮助你尽量保持相同的排序结构的JSON格式的例子来看看:

AggregateIterable<Document> resultset =dbCollection.aggregate(Arrays.asList(
    new Document("$match", 
    new Document("machineID", new Document("$in", Arrays.asList("1","10"))) 
     .append("errorID", "error5") 
), 

    new Document("$group", 
    new Document("_id", 
     new Document("machineID", "$machineID").append("errorID","$errorID") 
    ).append("count", new Document("$sum",1)) 
), 

    new Document("$project", 
    new Document("machineID", "$_id.machineID") 
     .append("errorID", "$_id.errorID") 
     .append("count", "$count") 
     .append("_id", 0) 
) 
));