nathanpr
nathanpr

Reputation: 51

MongoOperations "id" selector returning null

I am using the MongoOperations interface in the Spring-data-mongodb 1.1.1.RELEASE and any query using "id" as selector returns null: Query.query(Criteria.where("id").is("5X")))

However, when I used the Mongo class withing the Java driver and run the query it works as expected. i.e.: dbCollection.find(Query.query(Criteria.where("id").is("5X")).getQueryObject()));

Based on my research, this should work for the MongoOperations interface, and the selector "id" should not clash with the "_id" selector. Has anyone run in to this issue, or anyone know what's going on?

Upvotes: 1

Views: 3245

Answers (2)

Andy Dudley
Andy Dudley

Reputation: 329

It doesn't like fields named "id" that aren't Document Id's. Use the @Field("id") annotation to map it in the class.

import org.springframework.data.mongodb.core.mapping.Field;
...
@Field("id") 
public int id;

Upvotes: 0

user
user

Reputation: 3088

The reason is that there is no id, but there is _id - try that. In mongodb, PK default field has "_id" name.

If you need to find documents only by id, why don't you use something like findById(id) in mongoTemplate if you use Spring or do something like that:

DBCollection coll = db.getCollection(getCollectionName());
DBObject searchById = new BasicDBObject("_id", new ObjectId(idString));
DBObject found = coll.findOne(searchById);

In spring mongo try:

YourObject obj= mongoTemplate.findOne(new Query(Criteria.where("id").is("5X")),  YourObject.class, "yourCollectionName");

Upvotes: 3

Related Questions