PDA

View Full Version : How do I retrieve only a subset of data from Mongo?



bjornharvold
Jul 15th, 2011, 11:56 AM
Let's say I want to retrieve a list of users from mongo, but I want to make the query faster by only returning the user data I will be working with.

E.g. autoCompleteUsername(username)

Result:
List<User>
Where only user.id and user.username are populated.

How would I do this?

In mongo it would look something like this:
db.testdb.user.find({"username" : /^johnsmi*/i}, {username:1}).skip(0).limit(30)

Cheers
bjorn

bjornharvold
Jul 22nd, 2011, 10:08 AM
Any resolution on this. I still haven't been able to figure this out.

Thanks
bjorn

Oliver Gierke
Jul 22nd, 2011, 11:09 AM
The Query class has a fields() method which returns a Fields object that you can programmatically set the fields to include or exclude. If you're using the repository abstraction there's an @Query annotation having a fields attribute, that takes a JSON string just as you posted above which can be equiped with placeholders (e.g. ?0) to reference method parameters.

bjornharvold
Jul 22nd, 2011, 12:15 PM
Thanks Oliver!