Sort documents in collections while fetching

后端 未结 2 1664
有刺的猬
有刺的猬 2021-01-20 11:18

I have a collection called at MongoDB called resource. It has the following documents:

{ \"_id\" : \"Abb.e\", \"_class\" : \"Resource\", \"resourceEmail\" :          


        
2条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-20 11:36

    Should be something like this:

     MongoOperations mongoOperations = mongoConfiguration.getMongoTemplate();
      List resourceList = mongoOperations.findAll(Resource.class).sort({'_id' : 1});
      return resourceList;
    

    You need to append .sort({'_id' : 1}) for ascending order or .sort({'_id' : -1}) for descending order.


    For Java:

    .sort( new BasicDBObject( "_id" , 1 ) )
    

    Solution from echo:

    DBCursor dbCursor = mongoOperations.getCollection(RESOURCE_COLLECTION_NAME).find().sort(new BasicDBObject("_id", 1)); 
    List dbObjects = dbCursor.toArray(); 
    List items = new ArrayList(dbCursor.length()); 
    for (DBObject dbObject : dbObjects) { 
     Map map = dbObject.toMap(); 
     items.add(dbObject.toMap()); 
    }
    

提交回复
热议问题