2016-07-30 19 views
0

Ich frage mich, wie die Aggregation $ match auf eine $ lookup Sammlung mit dem java Treiber für mongodb 3.2. Hier ist die Struktur der beiden Sammlungen an dem ich arbeite:mongodb 3.2 java driver aggregation whith match auf lookup

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 } 

Das Nachschlagen auf den beiden IDs (coll_one.foreign_id & coll_two._id) scheint gut zu funktionieren. Wenn ich jedoch eine Übereinstimmung für coll_two.actif = true festlege, wird ein leeres Ergebnis zurückgegeben.

Dies ist der Java-Code i'am mit:

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 funktioniert whene i das Spiel Abschnitt zu entfernen. Ich habe so viele Kombinationen von Möglichkeiten ausprobiert, ohne Erfolg !!!

Kann mir irgendjemand sagen, ob das möglich ist ????

+0

Ihr Code tun Arbeiten mit den Beispieldaten auf meinem Rechner. Überprüfen Sie, ob Ihre Daten wirklich Ihren Erwartungen entsprechen. Zum Beispiel ist actif boolesch ** true ** nicht string "true". Sie können auch versuchen, die Matchstufe als ein Dokument zu definieren: 'Bson match = new Document (" $ match ", neues Dokument (" look_coll.actif ", true));' –

Antwort

0

Fügen Sie Ihre $match Anfrage an ein Document Beispiel:

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

filters.add(match); 

Hier ist ein vollständiges Beispiel:

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