How to frame a query using @Query annotation?

titogeo picture titogeo · Sep 5, 2012 · Viewed 13.2k times · Source

Is there any way to represent below query using spring-data mongo @Query annotation.

db.users.find({userName: "titogeo"}, {requests: 1, _id:0})

The above query output in console is

requests" : [{"who" : "blahblahblah1",
"whom" : "blahblahblah2",
"what" : "REQUEST",
"when" : ISODate("2012-09-05T17:52:14.339Z") } ] }

I tried the following but did not work.

@Query("{userName: ?0}, {requests:1, _id:0}")
public Page<AddRequest> getAllFriendRequests(String userName, Pageable pageable);

Collection users has User objects and requests is a list in it contains AddRequest objects.

When I execute the above method, i am getting a blank list. Any help is appreciated.

Also is there any good reference sites or books for spring-data-mongo apis?

Answer

Louisa picture Louisa · Sep 5, 2012

Since you are using the filter property to restrict the set of properties that get returned (just requests), you need to use the property keywords in the following syntax:

@Query(value = "{ 'userName' : ?0 }", fields = "{ 'requests': 1, '_id': 0 }")
public Page<AddRequest> getAllFriendRequests(String userName, Pageable pageable);

Here is a helpful site for spring-data mongodb: http://static.springsource.org/spring-data/data-document/docs/current/reference/html/