This question already has an answer here:
MongoDB : Sorting Data when using DBcollection find

(1个答案)


在8个月前关闭。





我正在使用此驱动程序https://mongodb.github.io/mongo-java-driver/3.4/driver/getting-started/quick-start/

MongoCollection<Document> collection = database.getCollection("blogs");
String text = "hey";
List<String> searched = new ArrayList<String>();
// MongoCursor<Document> cursor = collection.find("posts").sort(ascendingorder).iterator()


博客集合具有1个变量的json倍数

{
    "_id": "randomid"
    "posts": "hey my name is bob"
},

{
    "_id": "randomid"
    "posts": "a hey my name is bob"
},


如果要在此示例中找到搜索到的文本的“嘿”,我想将每个json从升序排序到一个列表中。所有帖子按升序包含“嘿”

例如上面的列表是

searched = [
    {
        "_id": "randomid"
        "posts": "a hey my name is bob"
    },

    {
        "_id": "randomid"
        "posts": "hey my name is bob"
    }

]

最佳答案

随机ID将是mongodb创建的时间戳。您可以使用它进行排序。

-1: descending order
 1: ascending order

 You can query like this:
 myDoc = coll.find(finalQuery).sort(new BasicDBObject("_id", -1));

关于java - mongodriver升序排列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58725897/

10-09 13:31