2016-07-30 7 views
0

mongodb 3.2のjavaドライバを使用して、$ルックアップコレクションで集計$ matchを実行する方法を知りました。ここで私は働いている2つのコレクションの構造は次のとおりです。mongodb 3.2検索でのJavaドライバ集約whith

coll_one:{ 
_id : ObjectId("hex_string"), 
foreign_id : ObjectId("hex_string") **the id of coll_two**} 

coll_two:{ 
_id : ObjectId("hex_string"), 
actif : true, 
closed : false } 

2つのID(& coll_two._idをcoll_one.foreign_id)の検索が正常に動作するようです。しかし、coll_two.actif = trueで一致を指定すると、空の結果が返されます。

これは、使用してJavaコードi'amです:私はマッチセクションを削除whene

Bson lookup = new Document("$lookup", 
new Document("from", "coll_two" ) 
.append("localField", "foreign_id") 
.append("foreignField", "_id") 
.append("as", "look_coll")); 

List<Bson> filters = new ArrayList<Bson>(); 
filters.add(lookup); 

//here is the MATCH 
filters.add(match(eq("look_coll.actif",true))); 

DB().getCollection("coll_one").aggregate(filters); 

Evrythingが正常に動作します。私は可能性の非常に多くの組み合わせを全く成功させずに試みました!

これが可能かどうかは、どのボディからでもわかりますか?

+0

あなたのコードは、私のマシン上のデータ例で動作を行います。あなたのデータが本当にあなたが期待しているものであることを確認してください。たとえば、actifはboolean ** true **で、文字列 "true"ではありません。また、マッチステージをドキュメントとして定義することもできます: 'Bson match = new Document(" $ match "、新しいドキュメント(" look_coll.actif "、true));' –

答えて

0

Documentインスタンスにご$match要求を追加します。ここでは

Bson match = new Document("$match", 
       new Document("look_coll.actif", true)); 

filters.add(match); 

は完全な例である:

MongoClient mongoClient = new MongoClient("localhost"); 

MongoDatabase db = mongoClient.getDatabase("mydb"); 

Bson lookup = new Document("$lookup", 
     new Document("from", "coll_two") 
       .append("localField", "foreign_id") 
       .append("foreignField", "_id") 
       .append("as", "look_coll")); 

Bson match = new Document("$match", 
     new Document("look_coll.actif", true)); 

List<Bson> filters = new ArrayList<>(); 
filters.add(lookup); 
filters.add(match); 

AggregateIterable<Document> it = db.getCollection("coll_one").aggregate(filters); 

for (Document row : it) { 
    System.out.println(row.toJson()); 
} 
関連する問題