Sanandrea
Sanandrea

Reputation: 2194

MongoDB update ObjectId field

I have a document that has an attribute which is an ObjectId. For example anchor field in the code below:

{ "__v" : 0, "_id" : ObjectId("5654d896481c5186ddaf4481"), "anchor" : ObjectId("565480e5481c5186ddaf446c"), "base_url" : "http://example.com"}

I saw the documentation here but it is not clear how to update an ObjectId reference field. I want this reference to just point to another anchor document, can I just place the ObjectId as a string like this:

db.categories.update(
   { },
   {
      $set {anchor: "5654d47a481c5186ddaf4479"}
   },
   { multi: true }
)

Upvotes: 1

Views: 5075

Answers (1)

katy lavallee
katy lavallee

Reputation: 2771

You can use ObjectId():

db.categories.update(
   { },
   {
      $set: { anchor: ObjectId("5654d47a481c5186ddaf4479") }
   },
   { upsert: true }
)

https://docs.mongodb.org/manual/reference/object-id/#core-object-id-class

The mongo shell provides the ObjectId() wrapper class to generate a new ObjectId,...

Upvotes: 7

Related Questions