When I type this into my consol, it works:
db.posts.find({"_id": {$lt:ObjectId("55732dccf58c555b6d3f1c5a")}}).limit(5).sort({"_id":-1})
When I use mongotemplate, it doesn't work and returns a blank array:
@RequestMapping(value="/next", method=RequestMethod.GET)
public List getNextPost(@RequestParam String next) {
Query query = new Query();
query.addCriteria(Criteria.where("_id").lt("55732dccf58c555b6d3f1c5a"));
List<Posts> posts = template.find(query, Posts.class);
return posts;
}
I tried it with this query instead and it works but only returns the specific entry related to the id:
query.addCriteria(Criteria.where("_id").is("55732dccf58c555b6d3f1c5a"));
I also tried with Basic Query and did this and it also returns a blank array:
BasicQuery query1 = new BasicQuery("{'_id': {$lt:'ObjectId(\"55732dccf58c555b6d3f1c5a\")'}}).limit(5).sort({'_id':-1}");
I'm stumped. How do I return all the docs below a certain Mongo ObjectID in a database?
So after searching for an hour, I have found the solution - i had to look at this post which is not in java but in node.js.
Querying a MongoDB based on Mongo ID in a node.js app
Thankfully, the language is close to java so I saw that you cannot query by just inserting the objectID into the lt operator. You will have to create an objectID object and insert that into the operator.