0

我想知道如何使用mongodb 3.2的 java 驱动程序对 $lookup 集合执行聚合 $match 。这是我正在研究的两个集合的结构:

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 }

对两个 id (coll_one.foreign_id & coll_two._id) 的查找似乎工作正常。但是当我在 coll_two.actif = true 上指定一个匹配项时,它返回一个空结果。

这是我正在使用的 Java 代码:

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

当我删除匹配部分时,一切工作正常。我尝试了很多可能性的组合,但都没有成功!!!

任何机构都可以告诉我这是否可能????

4

1 回答 1

0

将您的$match请求添加到Document实例:

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());
}
于 2016-07-30T14:18:21.243 回答