在 Spring Data (Mongodb) 中实现排序的问题
我需要使用 spring data api 执行以下 sql 查询:
Select * from TagTest where tagName = "water temperature" Order by timestamp desc;
我想出了查询:
Query query = new Query(Criteria.where("tagName").is("water temperature"));
我将 Sort
定义为:
query.sort().on("timestamp", Order.DESCENDING);
并且使用 mongoTemplate 执行 findOne()
类似:
mongoTemplate.findOne(Collection, query, MongoTag.class);
但是我找不到应用排序来检索 findOne
中结果的方法。 方法正确吗?如果我错了,请告诉我正确的方法。 谢谢。
I need to do the following sql query using spring data api:
Select * from TagTest where tagName = "water temperature" Order by timestamp desc;
I came up with the query:
Query query = new Query(Criteria.where("tagName").is("water temperature"));
I defined Sort
as:
query.sort().on("timestamp", Order.DESCENDING);
and the using mongoTemplate do findOne()
like:
mongoTemplate.findOne(Collection, query, MongoTag.class);
But I cannot find a way to apply the sort to retrieve results in findOne
.
Is the approach correct? Please let me know the correct approach in case I am wrong.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(3)
幸福不弃2024-12-11 20:33:57
你可以这样使用它:
public List<Person> listPersons() {
Criteria criteria=Criteria.where("tagName").is("water temperature"));
Query query = new Query();
query.addcriteria(criteria);
query.with(new Sort(Sort.Direction.ASC,"dateCreated")) ;
return mongoTemplate.find(query, Person.class);
}
我认为这是对你的问题的回答。
~没有更多了~
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
首先,Mongo 不是 SQL 数据库,因此您永远不会在其上运行任何 SQL。我建议花一些时间在 Mongo 命令行上熟悉 Mongo 中文档查询的工作方式 - 它在某些方面与 SQL 非常不同,但在其他方面完全相同。我还阅读了 Mongo 文档,这非常好: http://www.mongodb.org/display/DOCS/Home" rel="nofollow">http://www.mongodb.org/display/DOCS/Home" mongodb.org/display/DOCS/Home。
其次,查看您想要的“SQL”查询,看起来您想要所有 TestTags,而不仅仅是一个。
findOne
正如它所说的那样 - 返回一条记录。您可能想使用find
来代替。一个好的起点可能是弄清楚您将在 mongo 命令行上运行什么并从那里开始工作。
您不能同时使用
findOne
和排序,但应该能够使用findAll
和排序。如果您只想要一个结果,您可以为查询添加一个限制:我相信query.limit(1)
。First of all, Mongo isn't a SQL database, so you will never be running any SQL on it. I recommend spending some time on the Mongo command line to familiarise yourself with the way querying for documents works in Mongo - it's very different to SQL in some ways, exactly the same in others. I'd also have a read of the Mongo documentation, which is pretty good: http://www.mongodb.org/display/DOCS/Home.
Secondly, looking at the 'SQL' query you're aiming for, it looks like you want all the TestTags, not just one.
findOne
does just what it says - returns a single record. You probably want to usefind
instead.A good place to start is probably to work out what you'd be running on the mongo command line and work from there.
You can't use
findOne
and sort together, but you should be able to usefindAll
and sort together. And if you only want one result, you can add a limit to the query:query.limit(1)
I believe.