Mongotemplate-根据大于(gt)或小于(lt)运算符查询ObjectId [英] Mongotemplate - Query ObjectId according to greater than (gt) or less than (lt) operator
问题描述
当我在控制台上键入它时,它会起作用:
When I type this into my consol, it works:
db.posts.find({"_id": {$lt:ObjectId("55732dccf58c555b6d3f1c5a")}}).limit(5).sort({"_id":-1})
当我使用mongotemplate时,它不起作用并返回一个空白数组:
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;
}
我改用此查询尝试了该方法,它可以工作,但只返回与id相关的特定条目:
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"));
我还尝试了Basic Query并做到了,它还返回了一个空白数组:
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}");
我很困惑.如何在数据库中某个Mongo ObjectID下返回所有文档?
I'm stumped. How do I return all the docs below a certain Mongo ObjectID in a database?
推荐答案
因此,在搜索了一个小时之后,我找到了解决方案-我不得不看这篇不是Java而是在node.js中的帖子.
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.
根据以下内容查询MongoDB node.js应用中的Mongo ID
非常感谢,该语言非常接近java,所以我看到仅将objectID插入lt运算符就无法进行查询.您将必须创建一个objectID对象,并将其插入到运算符中.
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.
ObjectId objID = new ObjectId("55732dccf58c555b6d3f1c5a");
query.addCriteria(Criteria.where("_id").lt(objID));
这篇关于Mongotemplate-根据大于(gt)或小于(lt)运算符查询ObjectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!