5

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"))
);

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"))
);

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.

Community
  • 1
  • 1
Alexander
  • 335
  • 1
  • 4
  • 12
  • Possible duplicate of [How to query documents using "\_id" field in Java mongodb driver?](http://stackoverflow.com/questions/9797935/how-to-query-documents-using-id-field-in-java-mongodb-driver) – chridam Oct 04 '15 at 12:48

3 Answers3

12

You're currently trying to update based on a string, not an 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"))
);
sheilak
  • 5,833
  • 7
  • 34
  • 43
2

@sheilak's answer is the best one but,

You could use {"_id", {"$oid","56110fe1f882142d842b2a63"}} as the filter for the update query if you want it to be in the string format

varunarl
  • 291
  • 3
  • 4
  • Can you explain me a bit how can I use below document to updateOne:- ```{ "_id": { "$oid": "6148079b34f0a9e6mhghkgjvjh" }, "CUST_CODE": "in1", "name": "emp1", "designation": "tester", "address": { "Street": "main1", "country": "CN" } }``` – Dunggeon Sep 28 '21 at 06:24
-1

Convert the string to objectid:

from bson.objectid import ObjectId
db.collection.find_one({"_id":ObjectId('5a61bfadef860e4bf266edb2')})

{u'_id': ObjectId('5a61bfadef860e4bf266edb2'), ...
June7
  • 19,874
  • 8
  • 24
  • 34
zKaj
  • 9
  • 4