【问题标题】:mongodb 3.2 java driver aggregation whith match on lookupmongodb 3.2 java驱动程序聚合与查找匹配
【发布时间】:2016-07-30 12:00:09
【问题描述】:

我想知道如何使用 用于 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);

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

谁能告诉我这是否可能????

【问题讨论】:

  • 您的代码确实适用于我机器上的示例数据。检查您的数据是否真的是您所期望的。例如,actif 是布尔值 true 而不是字符串“true”。您也可以尝试将匹配阶段定义为文档:Bson match = new Document("$match", new Document("look_coll.actif", true));

标签: mongodb lookup mongo-java-driver


【解决方案1】:

将您的 $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());
}

【讨论】:

    猜你喜欢
    • 2020-06-29
    • 2016-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    • 2016-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多