I am using java pojo's and spring MongoTemplate, I spent few hours now, trying to understand why MongoDb will not update an existing Document
I am able to insert documents, but not to update existing ones
Any simple way to trace this in mongo/spring?
I tried so far:
Simply call save:
person.setUpdateDate(new Date());
mongoTemplate.save(person);
//not working
call updateFirst
mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(person.getId())),
Update.update("objName", "NotWorking"),Person.class);
Get the collection first, convert to DB Object, then find and modify:
DBCollection coll=mongoTemplate.getCollection("Person");
DBObject mongoPerson = morphia.toDBObject(person);
DBObject afterSave = coll.findAndModify(new BasicDBObject("id", person.getId()), mongoPerson);
//afterSave is null
Try find by _id, then save:
DBObject mongoPerson = morphia.toDBObject(person);
Person found1 = mongoTemplate.findById(person.getId(), Person.class);
found1.setObjName(person.getName());
mongoTemplate.save(found1);
Find first, then save using "_id":
DBCursor found = coll.find(new BasicDBObject("_id", person.getId()));
DBObject first = found.next();
mongoTemplate.save(first);
Find first, then save using "id":
DBCursor found = coll.find(new BasicDBObject("id", person.getId()));
DBObject first = found.next();
mongoTemplate.save(first);
Try find and modify then save:
DBObject afterSave = coll.findAndModify(new BasicDBObject("id", person.getId()), mongoPerson);
//afterSave is null
mongoTemplate.save(person);
Update individual fields using query:
Query query = new Query();
query.addCriteria(Criteria.where("_id").is(person.getId()));
mongoTemplate.updateFirst(query, new Update().set("name",person.getName())
.set("desc", person.getDesc())
.set("updateDate",new Date())
,
Person.class)
*Update this is also working:
mongoOperations.save(person,"Person");
Using this article I was able to make update work - not the way I want, but...It works...
import static org.springframework.data.mongodb.core.query.Criteria.where;
import static org.springframework.data.mongodb.core.query.Query.query;
import static org.springframework.data.mongodb.core.query.Update.update;
@Controller
public class PersonController {
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
MongoOperations mongoOperations;
...
mongoOperations.updateFirst(query(where("_id").is(person.getId())), Update.update("name", newPersonName),"Person");
Not sure yet why this work while
mongoOperations.save(person);
Is not working...