【发布时间】:2019-02-13 18:57:47
【问题描述】:
我正在尝试按 Java 对子文档进行排序。我无法找到所需的输出。我的数据集是:
[
{
"_id": {
"$oid": "5b91668a0f77e30c11574c88"
},
"driverId": "22",
"busId": "55",
"startTime": {
"$date": 1536255626852
},
"location": [
{
"latitude": 18.5803721,
"longitude": 73.7447051,
"position": 0,
"status": 1,
"time": {
"$date": 1536255628848
}
},
{
"latitude": 18.5803721,
"longitude": 73.7447051,
"position": 1,
"status": 2,
"time": {
"$date": 1536255656122
}
},
{
"latitude": 18.5803721,
"longitude": 73.7447051,
"position": 1,
"status": 2,
"time": {
"$date": 1536255656167
}
}
]
},
{
"_id": {
"$oid": "5b8c2cc70f77e322617c1ba1"
},
"driverId": "22",
"busId": "55",
"startTime": {
"$date": 1535913159533
},
"location": [
{
"latitude": 18.5804663,
"longitude": 73.7447209,
"position": 0,
"status": 1,
"time": {
"$date": 1535913160226
}
},
{
"latitude": 18.5804663,
"longitude": 73.7447209,
"position": 1,
"status": 2,
"time": {
"$date": 1535913186460
}
},
{
"latitude": 18.5804663,
"longitude": 73.7447209,
"position": 1,
"status": 2,
"time": {
"$date": 1535913187603
}
}
]
}
]
还有我写的代码:
AggregateIterable<Document> findIterable = tripsCollection.aggregate(Arrays.asList(
new Document("$match", new Document("busId", busId)),
new Document("$sort", new Document("startTime", -1)),
new Document("$sort", new Document("location.position", -1))));
当我按 _Id 或 startTime 对文档进行排序时,会相应地输出。但是当我尝试对子文档进行排序时,结果集不会改变。
我也尝试了其他一些变化:
Bson bsonFilterBus = Filters.eq("busId", busId);
Bson sortByDate = descending("startTime");
Bson sortByPosition = descending("location.position");
FindIterable<Document> findIterable = tripsCollection.find(bsonFilterBus).sort(sortByDate).sort(sortByPosition);
但结果是一样的。即不根据 location.position 排序
我正在使用 MongoDb 4.0。在我读到的某处,Mongo DB 没有提供任何对子文档进行排序的方法。请帮帮我。
【问题讨论】:
标签: java mongodb mongodb-query aggregation-framework