开发者

Problem with implementing Sort in Spring Data (Mongodb)

开发者 https://www.devze.com 2023-04-04 22:09 出处:网络
I need to do the following sql query using spring data api: Select * from TagTest where tagName = \"water temperature\" Order by timestamp desc;

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.


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 use find 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 use findAll and sort together. And if you only want one result, you can add a limit to the query: query.limit(1) I believe.


Why are you running a findOne and then trying to sort it? Have you tried that in traditional SQL? It does not make sense. Otherwise you are on the right path. Try the following, it worked for me:

public List<Person> listPersons() {
    Query query = new Query();
    query.limit(MAX_ROWS)
        .sort().on("dateCreated", Order.ASCENDING);

    return mongoTemplate.find(query, Person.class);
}


You can use it like this :

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);
}

is the response to your question i think.

0

精彩评论

暂无评论...
验证码 换一张
取 消