基于id我必须更新mongodb数据库中的字段。我使用的是spring-mvc,angularjs和mongodb。我正在参加我的春季班,但没有更新。我正在给一个mongodb数据样本。从那个数据我必须更新状态字段。
//mongodb
{ "_id" : ObjectId("556459bc4f3c9aac453f711d"),
"name" : "TestTask3",
"type" : null,
"status" : "Pending Approval",
"detail" : "TEst",
"comments" : "TEst"
}
//Spring class
public void approveTask(String id){
try {
DBCollection collection = mongoTemplate.getCollection(RelmanUtil.MONGO_DB_COLL_TASKS);
BasicDBObject query = new BasicDBObject("_id",id);
BasicDBObject update = new BasicDBObject();
update.put("$set", new BasicDBObject("status", "Assigned"));
collection.update(query, update);
} catch (Exception e) {
e.printStackTrace();
}
}
答案 0 :(得分:2)
您错过了将id
作为字符串传递给mongo ObjectId
check this的内容,您应该更改以下代码:
import org.bson.types.ObjectId;
public void approveTask(String id) {
try {
DBCollection collection = mongoTemplate.getCollection(RelmanUtil.MONGO_DB_COLL_TASKS);
BasicDBObject query = new BasicDBObject("_id", ObjectId(id));
//OR BasicDBObject query = new BasicDBObject("_id", new ObjectId(id));
BasicDBObject update = new BasicDBObject();
update.put("$set", new BasicDBObject("status", "Assigned"));
collection.update(query, update);
} catch(Exception e) {
e.printStackTrace();
}
}
将id
放入ObjectId(id) or new ObjectId(id)