我很难创建与以下mongo $ group的 $ push部分等效的Java:
db.crewtrades.aggregate(
{
$group:
{
_id: {staffId: '$initiatingStaffId', status: '$status', firstName: '$initiatingStaffFirstName'},
count:{'$sum':1}
}
},
{
$group:
{
_id:'$_id.staffId',
name: {$first: '$_id.firstName'},
statuses:
{
$push:
{
status:'$_id.status',
count:'$count'
}
},
staffCount: {$sum: '$count'}
}
}
)
结果应如下所示:
{
"_id" : "00238061",
"name" : "Kirstie Rachel Wong",
"statuses" : [
{
"status" : "Pending",
"count" : 1.0
},
{
"status" : "Approved",
"count" : 2.0
}
],
"staffCount" : 3.0
}
我尝试了以下方法:
private List<Bson> createPipeline(String companyCode, String startDate, String endDate, String eventType, List<String> eventConfigIds, String requestType, String staffId, String status) {
return Arrays.asList(
match(and(getBsons(companyCode, startDate, endDate, eventConfigIds, requestType, staffId, status)
)),
(group("_id", createIdFields(startDate, endDate, eventType))),
(group("$staffId",
first("firstName", "$firstName"),
first("lastName", "$lastName"),
first("startDate", "$startDate"),
first("endDate", "$endDate"),
first("eventType", "$eventType"),
first("requestType", "$requestType"),
push("statuses", createPushFields()),
sum("staffCount", "$count")
)));
}
private DBObject createPushFields() {
return new BasicDBObject("status","$status").append("count","$count");
}
private List<BsonField> createIdFields(String startDate, String endDate, String eventType) {
ArrayList<BsonField> fields = new ArrayList<>();
fields.add(first("staffId", "$initiatingStaffId"));
fields.add(first("firstName", "$initiatingStaffFirstName"));
fields.add(first("lastName", "$initiatingStaffLastName"));
fields.add(push("status", "$status"));
fields.add(first("startDate", startDate));
fields.add(first("endDate", endDate));
fields.add(first("eventType", eventType));
fields.add(first("requestType", "$tradeBoardId"));
fields.add(sum("count", 1));
return fields;
}
但是最终返回:
[
{
"_id": "00238061",
"firstName": "Kirstie Rachel Wong",
"lastName": "Wong",
"startDate": "2018-01-01T16:30:40Z",
"endDate": "2018-12-12T16:30:40Z",
"eventType": "DutySwap",
"requestType": 0,
"statuses": [
{
"status": [
"Approved",
"Approved",
"Pending"
],
"count": 3
}
],
"staffCount": 3
}
]
我应该如何在Mongo Java代码中指定状态(“已批准”,“待处理”)和每个状态的计数应为statuses数组内的JSON对象? Mongo本机查询能够很好地处理此问题,但是我无法让Java驱动程序执行相同的操作。
对此表示感谢!