我们正在插入带有标识符的mongo文档,并且文档中有一个子数组。
[0 0 595 842]
我想根据公司ID检索公司详细信息,并将人员合并到一个数组列表中,并根据加入日期对人员进行排序。
目前我可以使用QueryBuilder来检索数据,但是我无法根据日期对人进行排序。我可以使用java比较器来做同样的事情,但我正在查看是否有来自mongo db java的任何API可以用来获得相同的驱动程序。
感谢。
答案 0 :(得分:4)
您应该使用mongo aggregation首先$unwind persons
数组,然后按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);
}