2016-02-15 90 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); 
     } 
    } 
} 
相關問題