使用Java的Mongo 3.2驱动程序的新聚合功能

时间:2016-04-01 09:01:06

标签: java mongodb join

我想在Mongo 3.2中执行聚合,如此处所述,但在Java中:

https://docs.mongodb.org/master/reference/operator/aggregation/lookup/#pipe._S_lookup

目前我在java中的查询对象非常简单:

    Document query = new Document();

    query.append("employeId", employeId);

除了通过employeId过滤,我想加入这个集合与公司(其中employee.company_id = company.id)

我怎么能用Java做到这一点?好像我找不到这个新的Mongo功能的文档。

修改

员工收集示例:

{
    "id" : 1,
    "name" : "John",
    "lastName" : "Moore",
    "age" : 44,
    "companyId": 10 
}

公司集合示例:

{
    "id" : 10,
    "companyName" : "Microsoft",
    "numEmployee" : 100
}

预期输出的示例

{
    "id" : 1,
    "name" : "John",
    "lastName" : "Moore",
    "companyId" : 10,
    "companyName" : "Microsoft"
}

1 个答案:

答案 0 :(得分:2)

运行以下聚合管道应该为您提供所需的结果

pipeline = [
    {
        "$match": {
            "_id": employeeId
        }
    },
    {
        "$lookup": {
            "from": "company", 
            "localField": "companyId",
            "foreignField": "_id",
            "as": "company"
        }
    },
    {
        "$project": {
            "name": 1,
            "lastName": 1,
            "companyId": 1,
            "companyName": "$company.companyName"
        }
    }
];
db.employee.aggregate(pipeline);

Java测试实施

public class JavaAggregation {
    public static void main(String args[]) throws UnknownHostException {

        MongoClient mongo = new MongoClient();
        DB db = mongo.getDB("test");

        DBCollection coll = db.getCollection("employee");

        // create the pipeline operations, first with the $match
        DBObject match = new BasicDBObject("$match",
            new BasicDBObject("_id", employeeId)
        );

        // build the $lookup operations
        DBObject lookupFields = new BasicDBObject("from", "company");
        lookupFields.put("localField", "companyId");
        lookupFields.put("foreignField", "_id");
        lookupFields.put("as", "company");      
        DBObject lookup = new BasicDBObject("$lookup", lookupFields);

        // build the $project operations
        DBObject projectFields = new BasicDBObject("name", 1);
        projectFields.put("lastName", 1);
        projectFields.put("companyId", 1);
        projectFields.put("companyName", "$company.companyName");       
        DBObject project = new BasicDBObject("$project", projectFields);

        List<DBObject> pipeline = Arrays.asList(match, lookup, project);

        AggregationOutput output = coll.aggregate(pipeline);

        for (DBObject result : output.results()) {
            System.out.println(result);
        }
    }
}