2016-02-15 54 views
1

我有一个包含联系人的集合,每个联系人文档具有firstNamelastName属性。MongoDb Java驱动程序v3.x和聚合框架

现在我想通过在版本3.2中使用Java和MongoDb Java驱动程序来查询数据库。

我尝试找到与连接的firstName + lastName的联系人。我的查询看起来像MongoDB的外壳下面:

db.getCollection('contacts').aggregate(
    { 
      $project:{ 
       fullName:{ 
        $concat: [ "$firstName", " ", "$lastName" ] 
       } 
      } 
     }, 
     { 
      $match:{ 
       fullName:"John Doe" 
      } 
     } 
); 

现在,我试图让我的周围MongoDB的Java驱动程序头部,以获得在Java中实现相同的:

AggregateIterable<Document> documents = contactUserCollection.aggregate(Arrays.asList(project(computed("fullName", "$firstName $lastName")), match(eq("fullName", firstLastName)))); 

但这不是加工。

有人有一个想法,我怎么能做到这一点?

谢谢

回答

1

你可以尝试以下方法:

/* 
    MONGO SHELL : 
    var pipeline = [   
     { 
      "$project": { 
       "otherfieldsA": 1, 
       "otherfieldsB": 1, 
       "otherfieldsC": 1, 
       "fullName": { 
        "$concat": [ "$fistName", " ", "$lastName" ] 
       } 
      } 
     } 
     { 
      "$match": { "fullName": "John Doe" } 
     } 
    ]; 
    db.contacts.aggregate(pipeline); 

*/ 

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

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

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

     // create the pipeline operations, build the $project operations 
     BasicDBList concatenate = new BasicDBList(); 
     concatenate.add("$firstName"); 
     concatenate.add(" "); 
     concatenate.add("$lastName"); 

     DBObject fullName = new BasicDBObject("$concat", concatenate); 

     DBObject fields = new BasicDBObject("otherfieldsA", 1); 
     fields.put("otherfieldsB", 1); 
     fields.put("otherfieldsC", 1); 
     fields.put("fullName", fullName); 

     DBObject project = new BasicDBObject("$project", fields); 

     // create the $match operator 
     DBObject match = new BasicDBObject("$match", 
          new BasicDBObject("fullName", "John Doe") 
         ); 
     AggregationOutput documents = coll.aggregate(match, project, group, sort); 

     for (DBObject result : documents.results()) { 
      System.out.println(result); 
     } 
    } 
} 
相关问题