New aggregation feature with Mongo 3.2 driver, usi

2020-05-29 07:07发布

I want to perform an aggregation in Mongo 3.2 as explained here, but in Java:

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

At the moment my query object in java is very simple:

    Document query = new Document();

    query.append("employeId", employeId);

In addition to filtering by employeId, I would like to join this collection with company (where employee.company_id = company.id)

How can I do that in Java? It seems like I cannot find documentation of this new Mongo feature.

EDIT

Example of Employee collection:

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

Example of Company collection:

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

Example of output expected

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

1条回答
看我几分像从前
2楼-- · 2020-05-29 07:22

Running the following aggregation pipeline should give you the needed result

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 test implementation

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);
        }
    }
}
查看更多
登录 后发表回答