2015-05-28 48 views
0

我们正在插入带有标识符的mongo文档,文档中有一个子数组。根据日期提取mongo文档

insert 1 : 

db.test.insert(
    { 
     "companyId" : "123", 
     "persons" : [ 
       { 
         "joiningDate" : NumberLong("1431674741623"), 
         "name" : "Rajesh" 
       } 
     ], 

}) 

insert 2 : 

db.test.insert(
    { 
     "companyId" : "123", 
     "persons" : [ 
       { 
         "joiningDate" : NumberLong("1431674741653"), 
         "name" : "Rahul" 
       } 
     ], 

}) 

我想中检索根据公司ID公司的细节和人员合并到一个数组列表,并根据加盟日期排序的人。

目前我能够使用QueryBuilder来检索数据,但我无法根据日期对人员进行排序。我可以使用java比较器来做同样的事情,但我正在查看是否有来自mongo db的任何API可以用来获得相同的Java驱动程序。

谢谢。

+0

为什么 'joiningDate' 数据类型是NumberLong? – gypsyCoder

+0

@gypsyCoder它应该是时代:) – Yogesh

+0

@gypsyCoder:这是我注意到的一个问题,日期被设置为mongo Db中的NumberLong。在java代码中,它是util包中的一部分,使用long in ms值。 – Amz

回答

4

你应该使用mongo aggregation像第一$unwindpersons阵列,然后排序persons.joiningDate然后group with push如下:

db.test.aggregate({ 
    "$match": { 
    "companyId": "123" // match companyId 
    } 
}, { 
    "$unwind": "$persons" //unwind person array 
}, { 
    "$sort": { 
    "persons.joiningDate": -1 //sort joining date 
    } 
}, { 
    "$group": { 
    "_id": "$companyId", 
    "persons": { 
     "$push": "$persons" //push all sorted data into persons 
    } 
    } 
}).pretty() 

对于这个代码转换成Java使用mongo java aggregation作为

// unwind persons 
DBObject unwind = new BasicDBObject("$unwind", "$persons"); 
// create pipeline operations, with the $match companyId 
DBObject match = new BasicDBObject("$match", new BasicDBObject("companyId", "123")); 
// sort persons by joining date 
DBObject sortDates = new BasicDBObject("$sort", new BasicDBObject("persons.joiningDate", -1)); // -1 and 1 descending or ascending resp. 
// Now the $group operation 
DBObject groupFields = new BasicDBObject("_id", "$companyId"); 
groupFields.put("persons", new BasicDBObject("$push", "$persons")); 
DBObject group = new BasicDBObject("$group", groupFields); 
// run aggregation 
List <DBObject> pipeline = Arrays.asList(match, unwind,sortDates, group); 
AggregationOutput output = test.aggregate(pipeline); 
for(DBObject result: output.results()) { 
    System.out.println(result); 
}