2017-06-13 16 views
0

mongoDBのクエリをJavacodeに変換しようとしていますが、mongoで適切な値を返していますが、javaコードで実行しているときにcountに対して適切な値が返されません(適切なmachineID、errorID nullとしてカウントし、代わりにレコード数を返す必要があります)。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) 
) 
));