如何在Java中使用ObjectID更新MongoDB中的文档

如何在Java中使用ObjectID更新MongoDB中的文档

本文介绍了如何在Java中使用ObjectID更新MongoDB中的文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要在这里完成的工作非常简单.我正在尝试更新MongoDB集合中的单个文档.当我使用任何字段(例如名称")查找文档时,更新查询成功.这是查询:

What I am trying to accomplish here is pretty simple. I am trying to update a single document in MongoDB collection. When I look up the document using any field, such as "name", the update query succeeds. Here is the query:

mongoDB.getCollection("restaurants").updateOne(
    new BasicDBObject("name", "Morris Park Bake Shop"),
    new BasicDBObject("$set", new BasicDBObject("zipcode", "10462"))
);

如果我尝试使用ObjectId查找文档,则该文档将不起作用,因为它与任何文档都不匹配.

If I try to lookup the document with the ObjectId, it never works as it doesn't match any document.

mongoDB.getCollection("restaurants").updateOne(
    new BasicDBObject("_id", "56110fe1f882142d842b2a63"),
    new BasicDBObject("$set", new BasicDBObject("zipcode", "10462"))
);

是否可以使该查询与对象ID一起使用?

Is it possible to make this query work with Object IDs?

我同意我的问题与,但是尝试更新文档时没有出现任何错误.就是什么都不匹配.

I agree that my question is a bit similar to How to query documents using "_id" field in Java mongodb driver? however I am not getting any errors while trying to update a document. It just doesn't match anything.

推荐答案

您当前正在尝试基于字符串而不是ObjectId进行更新.

You're currently trying to update based on a string, not an ObjectId.

在构建查询时,请确保从字符串初始化新的ObjectId:

Make sure to initialise a new ObjectId from the string when building your query:

mongoDB.getCollection("restaurants").updateOne(
    new BasicDBObject("_id", new ObjectId("56110fe1f882142d842b2a63")),
    new BasicDBObject("$set", new BasicDBObject("zipcode", "10462"))
);

这篇关于如何在Java中使用ObjectID更新MongoDB中的文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-11 03:30