简体   繁体   English

如何使用MongoDB 3.0 Java驱动程序执行聚合

[英]How to perform aggregation with MongoDB 3.0 java driver

I am trying to perform simple aggregation operation using MongoDB java driver (3.0). 我正在尝试使用MongoDB Java驱动程序(3.0)执行简单的聚合操作。 Help required on how to write the below mongo shell query using JAVA API. 需要有关如何使用JAVA API编写以下mongo shell查询的帮助。

db.coll.aggregate([
    { $project: {
        email_id: { $ifNull: [ "$email_id", " " ] },
        phone_num: { $ifNull: [ "$phone_num","NA" ] },
        id : 1,
        firstname :1,
        lastname :1,
        status : 1
        }
    },
    { $match: { status: "true"} },
    { "$group": {
        "_id": "$id",
        "details": { "$push": {
            "$concat": [ "$firstname", " ", "$lastname", " | ", "$email_id" , " | ", "$phone_num" ]
        }}
    }}
])

Here are the java driver queries for your shell queries 这是您的shell查询的Java驱动程序查询

MongoClient mongo = new MongoClient();    
MongoDatabase database = mongo.getDatabase("your_database");
        Document emailIdDoc = new Document("$ifNull",Arrays.asList("$email_id", " "));
        Document phoneNumDoc = new Document("$ifNull", Arrays.asList("$phone_num", "NA")); 
        Document projectDoc = new Document("$project" , new Document("email_id", emailIdDoc).append("phone_num", phoneNumDoc).append("id" , 1).append("firstname" , 1).append("lastname", 1).append("status", 1));
        Document matchDoc = new Document("$match", new BasicDBObject("status", "true"));
        Document groupDoc = new Document("$group", new Document("_id", "$id").append("details", new Document("$push", concat)));
        AggregateIterable<Document> aggregationResult = db.getCollection("your_collection").aggregate(asList(projectDoc, matchDoc, groupDoc));

With Deprecated methods 使用不推荐使用的方法

MongoClient mongo = new MongoClient();
    DB db = mongo.getDB("your_database");
    BasicDBObject emailId = new BasicDBObject("$ifNull",Arrays.asList("$email_id", " "));
    BasicDBObject phoneNum = new BasicDBObject("$ifNull", Arrays.asList("$phone_num", "NA"));
    DBObject project = new BasicDBObject("$project" , new BasicDBObject("email_id", emailId).append("phone_num", phoneNum).append("id" , 1).append("firstname" , 1).append("lastname", 1).append("status", 1));
    DBObject match = new BasicDBObject("$match", new BasicDBObject("status", "true")); 
    DBObject concat = new BasicDBObject("$concat", Arrays.asList( "$firstname", " ", "$lastname", " | ", "$email_id" , " | ", "$phone_num"));
    Document concatDoc = new Document("$concat", Arrays.asList( "$firstname", " ", "$lastname", " | ", "$email_id" , " | ", "$phone_num"));
    DBObject group = new BasicDBObject("$group", new BasicDBObject("_id", "$id").append("details", new BasicDBObject("$push", concat)));

    AggregationOutput iterable = db.getCollection("your_collection").aggregate(project, match, group);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM