我一直在尝试根据日期对存储在文档列表中的项目进行排序。这是我的文件的结构:
{
"_id": ObjectId("55c1940ce4b0a2a0482f22e8"),
"eventId": "45b73f69-4804-4b50-84d0-6c551aa5bb5c",
"isMacro": true,
"isDeleted": false,
"calendarEvent": [
{
"eventId": "b89a1519-ddff-4f71-9366-117e23c16d5c",
"startDateTime": ISODate("2017-04-16T10:00:00.000Z")
},
{
"eventId": "ecec8b3a-cf48-4f14-a7ac-14cd1a19f9da",
"startDateTime": ISODate("2014-03-25T10:00:00.000Z")
},
{
"eventId": "a002cc47-2939-4e75-9793-74720ebb7a21",
"startDateTime": ISODate("2015-09-10T10:00:00.000Z")
}
]
}
我想按calendarEvent
顺序对ASC
列表中的项目进行排序。我正在使用 Spring Data MongoDB 。
这是我的代码:
AggregationOperation unwind = Aggregation.unwind("calendarEvent");
AggregationOperation match = Aggregation.match(criteria);
AggregationOperation project = getEventProjectionFields(); //private function which returns project object.
AggregationOperation sort = Aggregation.sort(Direction.ASC,
"calendarEvent.startDateTime");
Aggregation aggregation = Aggregation.newAggregation(unwind, match,
project, skip(0), limit(5), sort);
AggregationResults<Event> groupResults = mongoTemplate.aggregate(
aggregation, mongoTemplate.getCollectionName(KAEvent.class),
Event.class);
return groupResults.getMappedResults();
打印aggregation.toString()
的值将返回以下JSON:
{
"aggregate": "__collection__",
"pipeline": [
{
"$unwind": "$calendarEvent"
},
{
"$match": {
"isMacro": true,
"isDeleted": false,
"$and": [
{
"eventId": {
"$in": [
"3d478f1a-9296-46b5-87d9-d0b442be0309",
"4cbbe84b-6a35-4797-8c06-9b9b679ca48c"
]
}
},
{
"calendarEvent.eventId": {
"$in": [
"cb3fb7e7-5444-4ca5-8a6b-09e74bd346e4",
"fec94eb6-160d-4608-8dae-5b43b88c550f",
"e33d11a1-6d36-49ce-9e84-9b83ee9445dd"
]
}
}
],
"calendarEvent.startDateTime": {
"$gte": {
"$date": "2015-10-13T07:42:48.841Z"
}
}
}
},
{
"$project": {
"eventId": "$calendarEvent.eventId",
"name": "$calendarEvent.name",
"eventDescription": "$calendarEvent.eventDescription",
"eventSummary": "$calendarEvent.eventSummary",
"eventLocation": "$calendarEvent.eventLocation",
"startDateTime": "$calendarEvent.startDateTime",
"endDateTime": "$calendarEvent.endDateTime",
"lastUpdateDate": "$calendarEvent.lastUpdateDate",
"eventUrl": "$calendarEvent.eventUrl",
"customImageUrl": "$calendarEvent.customImageUrl",
"tagsList": "$calendarEvent.tagsList",
"imagesList": "$calendarEvent.imagesList",
"isFeatured": "$calendarEvent.isFeatured",
"isDeleted": "$calendarEvent.isDeleted",
"providerId": 1,
"sourceId": 1,
"isMacro": 1,
"isCalendarEvent": 1,
"_class": "$calendarEvent._class",
"parenteventId": "$eventId"
}
},
{
"$skip": 0
},
{
"$limit": 5
},
{
"$sort": {
"calendarEvent.startDateTime": 1
}
}
]
}
毕竟,结果返回没有排序。我在这里错过了什么或做错了吗?
答案 0 :(得分:2)
在投影从嵌入字段startDateTime
派生的新字段"calendarEvent.startDateTime"
后,您正在进行排序。
将排序管道更改为
AggregationOperation sort = Aggregation.sort(Direction.ASC,
"startDateTime");