简体   繁体   English

我们可以在Java中使用_id更新mongodb中的文档吗?

[英]can we update a document in mongodb using _id in java?

I am trying update document with object id but not getting result. 我正在尝试使用对象ID更新文档,但没有得到结果。 Here is my code please help me 这是我的代码,请帮帮我

DBCollection patients= db.getCollection("Patients");
    BasicDBObject doc = new BasicDBObject();
            doc.put("name","seshu");


DBObject update=`new` BasicDBObject().append("_id",ObjectId("534e1c8e40a8af540cd01ff4"));

    patients`enter code here`.update(update, doc);

When you say "not getting result", I assume you mean that the document is not being updated? 当您说“没有得到结果”时,我想您是说文档没有被更新?

Are you sure that you have the collection name, database name, and ObjectId correct? 您确定集合名称,数据库名称和ObjectId正确吗? And that a document exists in that collection with that ObjectId. 并且该集合中存在带有该ObjectId的文档。 You should double check all of this via your program or the mongo shell. 您应该通过程序或mongo shell仔细检查所有这些。

Why don't you also try adding some extra checks/debugging in your code, something like this: 您为什么不还尝试在代码中添加一些额外的检查/调试功能,如下所示:

DBCollection patients = db.getCollection("Patients");
DBObject update = new BasicDBObject().append("_id", new ObjectId("..."));

long collectionCount = patients.count();
System.out.println(String.format("Collection count: %s", collectionCount));
long count = patients.count(update);
System.out.println(String.format("Count for query: %s", count));

BasicDBObject doc = new BasicDBObject();
doc.put("name", "seshu");


WriteResult writeResult = patients.update(update, doc);
System.out.println(String.format("Updated %s records", writeResult.getN()));

DBObject updated = patients.findOne(update);
System.out.println(updated);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM