Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring data + Mongodb + query single value?

Tags:

spring

mongodb

how to query a field instead of a whole object? I am trying to do something like that, want to see is that possible?

public BigInteger findUserIDWithRegisteredEmail(String email){

    Query query = Query.query(Criteria.where("primaryEmail").is (email));    
    query.fields().include("_id");

    return (BigInteger) mongoTemplate.find(query, BigInteger.class);    
}
like image 949
Jaxox Avatar asked Mar 25 '13 05:03

Jaxox


People also ask

How do I capture a specific field in MongoDB?

You can select a single field in MongoDB using the following syntax: db. yourCollectionName. find({"yourFieldName":yourValue},{"yourSingleFieldName":1,_id:0});

What is the difference between MongoOperations and MongoTemplate?

MongoTemplate provides a simple way for you to save, update, and delete your domain objects and map those objects to documents stored in MongoDB. You can save, update and delete the object as shown below. MongoOperations is the interface that MongoTemplate implements.

Can I use spring data JPA with MongoDB?

Yes, DataNucleus JPA allows it, as well as to many other databases. You make compromises by using the JPA API for other types of datastores, but it makes it easy to investigate them.


1 Answers

In method

find(Query query, Class<YourCollection> entityClass)

entityClass should be the corresponding collection, not the type of id.

If you are just trying to get id use

Query query = Query.query(Criteria.where("primaryEmail").is (email));    
query.fields().include("_id");
mongoTemplate.find(query, <YourCollection>.class).getId();

If you only include _id, all the other fields will be null in your result.

like image 94
titogeo Avatar answered Oct 02 '22 09:10

titogeo