Spring 更改 mongodb 的排序字段顺序
Spring change the sorting fields' order for mongodb
我尝试通过 Spring Sort
对象对 mongo 中的数据进行排序,其中包含 2 个特定字段。
出于某种原因,Spring 更改了 'sorting fields'.
的顺序
我使用 Spring 和 Mongo 数据库数据 (MongoTemplate
)。我使用 findAll()
函数来获取一些记录。
在 mongo 数据中,我有特定的索引 { "status": -1, "_id": -1 }
。
我想按这个特定的索引排序,为此我添加了这个排序代码:
new Sort(Sort.Direction.DESC, "status").and(new Sort(Sort.Direction.DESC,
"_id"));
我按 status
字段排序,然后按 _id
字段排序(如索引)。
仅供参考:
我使用其他索引并按它们排序,而 Spring 不对我的 'sorting fields':
排序
{ "status": -1, "__sort_authors": 1 }
{ "status": -1, "__sort_title": 1 }
在这些情况下,Spring 将排序字段的顺序保存在 Mongo 查询中:
查询:{...}, Sort: { "status":-1, "__sort_authors":1 }
查询:{...}, Sort: { "status":-1, "__sort_title":1 }
预期的 mongo 查询应该是:
{ "foldersIds" : { "$in" : ["project:6s5d4f32sd1f65"] }, "availability" : "PRESENT" }, Fields: { }, Sort: { "status" : -1, "_id" : -1 }
实际的mongo查询是:
{ "foldersIds" : { "$in" : ["project:5c505594e4b0e98a6537ec9d"] }, "availability" : "PRESENT" }, Fields: { }, Sort: { "_id" : -1, "status" : -1 }
可能是因为 _id
是主字段?
我想保持排序字段的顺序。知道如何保存订单吗?
谢谢!
我会尝试通过传递 List
而不是调用 and
方法来显式设置顺序。像这样:
ArrayList<Order> orders = new ArrayList<>();
orders.add(new Sort.Order(Sort.Direction.DESC, "status"));
orders.add(new Sort.Order(Sort.Direction.DESC, "_id"));
Sort sort = Sort.by(orders);
我建议这样做的原因是因为 Sort.and()
方法的文档只指定它组合指定的排序,它没有指定它如何或以什么顺序组合它们。使用 List
应该有望强制执行您想要的顺序。
我尝试通过 Spring Sort
对象对 mongo 中的数据进行排序,其中包含 2 个特定字段。
出于某种原因,Spring 更改了 'sorting fields'.
我使用 Spring 和 Mongo 数据库数据 (MongoTemplate
)。我使用 findAll()
函数来获取一些记录。
在 mongo 数据中,我有特定的索引 { "status": -1, "_id": -1 }
。
我想按这个特定的索引排序,为此我添加了这个排序代码:
new Sort(Sort.Direction.DESC, "status").and(new Sort(Sort.Direction.DESC,
"_id"));
我按 status
字段排序,然后按 _id
字段排序(如索引)。
仅供参考:
我使用其他索引并按它们排序,而 Spring 不对我的 'sorting fields':
排序{ "status": -1, "__sort_authors": 1 }
{ "status": -1, "__sort_title": 1 }
在这些情况下,Spring 将排序字段的顺序保存在 Mongo 查询中:
查询:{...}, Sort: { "status":-1, "__sort_authors":1 }
查询:{...}, Sort: { "status":-1, "__sort_title":1 }
预期的 mongo 查询应该是:
{ "foldersIds" : { "$in" : ["project:6s5d4f32sd1f65"] }, "availability" : "PRESENT" }, Fields: { }, Sort: { "status" : -1, "_id" : -1 }
实际的mongo查询是:
{ "foldersIds" : { "$in" : ["project:5c505594e4b0e98a6537ec9d"] }, "availability" : "PRESENT" }, Fields: { }, Sort: { "_id" : -1, "status" : -1 }
可能是因为 _id
是主字段?
我想保持排序字段的顺序。知道如何保存订单吗?
谢谢!
我会尝试通过传递 List
而不是调用 and
方法来显式设置顺序。像这样:
ArrayList<Order> orders = new ArrayList<>();
orders.add(new Sort.Order(Sort.Direction.DESC, "status"));
orders.add(new Sort.Order(Sort.Direction.DESC, "_id"));
Sort sort = Sort.by(orders);
我建议这样做的原因是因为 Sort.and()
方法的文档只指定它组合指定的排序,它没有指定它如何或以什么顺序组合它们。使用 List
应该有望强制执行您想要的顺序。