PDA

View Full Version : mongoTemplate update by ID not work?



leewill
Apr 21st, 2011, 09:08 AM
I'm using Spring Mongo 1.0.0M2. I tried to update a property in a document and it failed when query by ID. This is the mongo template configuration:


@Override
public Mongo mongo() throws Exception {
ServerAddress address = new ServerAddress( "127.0.0.1" , 27017);

MongoOptions options = new MongoOptions();
options.autoConnectRetry = true;
options.connectionsPerHost=10;
options.threadsAllowedToBlockForConnectionMultipli er=5;
options.maxWaitTime=6000;
options.connectTimeout=0;
options.socketTimeout=0;

Mongo mongo = new Mongo(address, options);
return mongo;
}

@Override
public MongoTemplate mongoTemplate() throws Exception {
MongoTemplate mongoTemplate = new MongoTemplate(mongo(), "ecl");
mongoTemplate.setMongoConverter(mappingMongoConver ter());
mongoTemplate.setUsername(USERNAME);
mongoTemplate.setPassword(PASSWORD);
return mongoTemplate;
}

// public String getMappingBasePackage() {
// return "dist.bo";
// }



The injected MongoOperations works for save document, update entire document. It also works fine when:


mongoTemplate.updateFirst("entityCollectionName",
query(where("name").is("object name")),
update("deleted", true));


but never work if the query is


query(whereId().is(the_document_id)),


The funny thing is, retrieving document by id with such query works fine:


mongoTemplate.findOne(query(whereId().is(the_docum ent_id)),
MyDoc.class);


I never found any tutorial/reference talking about update a property by query ID.

Did I miss something?

leewill
Apr 21st, 2011, 10:45 AM
it turned out not just me who got this problem:
http://forum.springsource.org/showthread.php?t=107358

leewill
Apr 21st, 2011, 01:13 PM
solved the problem. You can't use whereId().is(....). Here's my test codes:



Query q = query(whereId().is(new ObjectId(entity.getId())));
logger.info("query: " + q.getQueryObject());

WriteResult result = mongoTemplate.updateFirst(entityCollectionName,
q,
update("deleted", true));


This one will fail, and the query string in "q" is:
{ "id" : { "$oid" : "4db0718de0f46a0e2828532d"}}

But if change the whereId() to where("_id"), i.e.,


Query q = query(where("_id").is(new ObjectId(entity.getId())));

It works, and the query string in "q" is:
{ "_id" : { "$oid" : "4db0718de0f46a0e2828532d"}}

It seems whereId() in update has some issue, as it works perfect in save(), find()