2016-06-13 2 views
0

私はmongodbに80,000のドキュメントを持っています。私はJavaドライバを使用してこれらのドキュメントを照会しています。私は、特定のフィールドに基づいて私の文書を並べ替えて、この結果に明確なフィルターを適用しようとしました。並べ替えオプションはうまく動作しますが、別のドキュメントを取得できません。私は自分の仕事の例を添付しました。Javaで並べ替えと別のMongodb 3.2

Document query = new Document("RetweetCount",-1); 
    MongoCursor<Document> cursor = collection.find().sort(query).iterator(); 
    try{ 
    while(cursor.hasNext()) { 
     Document dr = (Document) cursor.next(); 
     String stat = dr.getString("status"); 
     int retweetcount = dr.getInteger("RetweetCount"); 
     //Sort works fine. I have to apply distinct here!!! distinct is based on status field 
     System.out.println(retweetcount+"--->"+stat); 
    } 
    }finally{ 
     cursor.close(); 
    } 
} 
+0

あなたは私にあなたのサンプルデータベースを教えてくれればhttp://api.mongodb.com/java/3.2/com/mongodb/operation/DistinctOperation.htmlを見たことがありますか少し考えてみてください – Newton

+0

@Netwon私のデータベース構造は{status:x、retweetcount:2}、{status:y、retweetcount:5}、{status:x、retweetcount:3}のようになります。新しいステータスとそのretweetcountで保存するたびに。私は状態のために一番上のretweetcountを取得する必要がありますが、私はdbに重複したステータスを持っています。私はステータスを取得したい:xとretweetcount:3、そのステータスのための最高のretweetcountを持っています。 – prabhu

+0

あなたのコレクションのバックアップを送信できますか? – Newton

答えて

0

私はこの方法を試みましたが、無関係なフィールドを取得しました。 I referred this link

ArrayList<Document> dd = new ArrayList<Document>(); 
    //MongoCursor<Document> cursor1 = collection.find().sort(query).iterator(); 

    Document grouping = new Document("_id","$status"); 
    grouping.append("text", new Document("$first","$_id")); 
    grouping.append("RetweetCount", new Document("$first","$RetweetCount")); 
    grouping.append("screen_name", new Document("$first","screen_name")); 
    Document group = new Document("$group",grouping); 
    System.out.println(group); 

    Document sortfields = new Document("RetweetCount",-1); 
    Document sort = new Document("$sort",sortfields); 

    Document projectfields = new Document("_id",0); 
    projectfields.append("_id", "$text"); 
    projectfields.append("RetweetCount", "$RetweetCount"); 
    projectfields.append("sn", "$screen_name"); 
    Document projects = new Document("$project",projectfields); 



    AggregateIterable<Document> iterable = collection.aggregate(asList(new Document(group),new Document(sort),new Document(projects))); 
    iterable.forEach(new Block<Document>() { 
     @Override 
     public void apply(final Document document) { 
      System.out.println(document.toJson()); 
     } 
    }); 

出力:

{ "_id" : { "$oid" : "576124fafbfb870794452ac6" }, "RetweetCount" : 643, "sn" : "screen_name" } 

それは私のテキストフィールドではなく、それはidフィールドを返し省略します。また、私のretweet順序が正しくありませんでした。 このメソッドは正常に動作しますが、結果は異なります。 誰でも私を修正してください!

+0

私は解決策を得ました。 – prabhu

関連する問題