关于 mongodb:Mongo 3.2 驱动的新聚合特性,使用 Java

New aggregation feature with Mongo 3.2 driver, using Java

我想按照这里的解释在 Mongo 3.2 中执行聚合,但是在 Java 中:

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

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

1
2
3
    Document query = new Document();

    query.append("employeId", employeId);

除了按employeeId过滤外,我还想将这个集合加入到公司中(其中employee.company_id = company.id)

如何在 Java 中做到这一点?好像我找不到这个新的 Mongo 功能的文档。

编辑

员工集合示例:

1
2
3
4
5
6
7
{
   "id" : 1,
   "name" :"John",
   "lastName" :"Moore",
   "age" : 44,
   "companyId": 10
}

公司集合示例:

1
2
3
4
5
{
   "id" : 10,
   "companyName" :"Microsoft",
   "numEmployee" : 100
}

预期输出示例

1
2
3
4
5
6
7
{
   "id" : 1,
   "name" :"John",
   "lastName" :"Moore",
   "companyId" : 10,
   "companyName" :"Microsoft"
}


运行以下聚合管道应该会给您所需的结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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 测试实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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);
        }
    }
}