我正在使用java pojo和spring MongoTemplate,我现在花了几个小时,试图理解为什么MongoDb不会更新现有的Document
我可以插入文档,但不能更新现有文档
在mongo / spring中有任何简单的方法来追踪它吗?
我到目前为止尝试过:
只需致电保存:
person.setUpdateDate(new Date());
mongoTemplate.save(person);
//not working
调用updateFirst
mongoTemplate.updateFirst(new Query(Criteria.where("_id").is(person.getId())),
Update.update("objName", "NotWorking"),Person.class);
首先获取集合,转换为DB对象, 然后找到并修改:
DBCollection coll=mongoTemplate.getCollection("Person");
DBObject mongoPerson = morphia.toDBObject(person);
DBObject afterSave = coll.findAndModify(new BasicDBObject("id", person.getId()), mongoPerson);
//afterSave is null
尝试按_id查找,然后保存:
DBObject mongoPerson = morphia.toDBObject(person);
Person found1 = mongoTemplate.findById(person.getId(), Person.class);
found1.setObjName(person.getName());
mongoTemplate.save(found1);
首先查找,然后使用“_id”保存:
DBCursor found = coll.find(new BasicDBObject("_id", person.getId()));
DBObject first = found.next();
mongoTemplate.save(first);
首先查找,然后使用“id”保存:
DBCursor found = coll.find(new BasicDBObject("id", person.getId()));
DBObject first = found.next();
mongoTemplate.save(first);
尝试查找并修改然后保存:
DBObject afterSave = coll.findAndModify(new BasicDBObject("id", person.getId()), mongoPerson);
//afterSave is null
mongoTemplate.save(person);
使用查询更新单个字段:
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)
答案 0 :(得分:0)
<强> *更新强> 这也有效:
mongoOperations.save(person,"Person");
Using this article我能够更新工作 - 不是我想要的方式,但是......它有效......
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");
时不确定为什么会这样做
mongoOperations.save(person);
不工作......
答案 1 :(得分:0)
您需要在方法中添加数据库名称 如:
public class UserInfoService{
public static final String INFO = "info";
public void someMethod(UserInfo userinfo){
mongo.save(userinfo, INFO);
}
如果你不这样做,mongo会将你的数据保存在db中,名称为userInfo(大写'I' )。