gpt4 book ai didi

java - 使用 java mongo db driver api 将数组作为 MongoDB 中的值进行排序

转载 作者:行者123 更新时间:2023-11-30 07:46:10 24 4
gpt4 key购买 nike

在 MongoDB 中使用数组作为值进行排序

我有一个包含两个字段的集合,一个以字符串作为值,第二个以字符串数组作为值。

例如

{"name" : "User-1",  "locations" : ["India", "USA", "UK"]}
{"name" : "User-2", "locations" : ["Russia", "UK", "USA"]}
{"name" : "User-3", "locations" : ["UK", "Japan", "India"]}
{"name" : "User-4", "locations" : ["Japan", "USA", "UK"]}
{"name" : "User-5", "locations" : ["India", "Italy", "Japan"]}

我想对“位置”字段进行排序。

输出必须是

{"name" : "User-5",  "locations" : ["India", "Italy", "Japan"]}
{"name" : "User-1", "locations" : ["India", "USA", "UK"]}
{"name" : "User-4", "locations" : ["Japan", "USA", "UK"]}
{"name" : "User-2", "locations" : ["Russia", "UK", "USA"]}
{"name" : "User-3", "locations" : ["UK", "Japan", "India"]}

我们如何使用 mongo db java 驱动程序 api 来做到这一点。

谢谢

最佳答案

您可以使用 "dot notation" 指定排序对于数组中的每个项目(按顺序):

 db.docs.find().sort({ "locations.0": 1, "locations.1": 1, "locations.2": 1 })

这会产生:

{ "name" : "User-5", "locations" : [ "India", "Italy", "Japan" ] }
{ "name" : "User-1", "locations" : [ "India", "USA", "UK" ] }
{ "name" : "User-4", "locations" : [ "Japan", "USA", "UK" ] }
{ "name" : "User-2", "locations" : [ "Russia", "UK", "USA" ] }
{ "name" : "User-3", "locations" : [ "UK", "Japan", "India" ] }

所以它基本上考虑了数组中每个元素的顺序偏好。

使用基本的 Java API,您只需提供相同的排序参数:

collection.find().sort(
new Document("locations.0",1)
.append("locations.1",1)
.append("locations.2",1)
);

关于java - 使用 java mongo db driver api 将数组作为 MongoDB 中的值进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33931804/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com