How to retrieve a subset of fields using the Java MongoDB driver?

new poster here, I found this previous post but it’s on C#, I tried doing this query straight into the java code of a JSP page, for some reason, it doesn’t accept the info in the {} of the find() query and just gives out an error…

So peeps, how do I do this in Java:

// retrieve ssn field for documents where last_name == 'Smith':
db.users.find({last_name: 'Smith'}, {'ssn': 1});


PS: why the hell does C# have the nice little .Exclude() and .Include() commands and java doesn’t? cries


The java driver follows the exact same API as the shell. Just pass a DBObject containing your field projection as the second argument to find or findOne

As far as I know the official C# driver doesn’t expose Include() and Exclude() methods as they violate the standard API.

Leave a Reply

Your email address will not be published. Required fields are marked *