0

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 }
)
Sanandrea
  • 2,112
  • 1
  • 27
  • 45

1 Answers1

6

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,...

katy lavallee
  • 2,741
  • 1
  • 28
  • 26
  • Hmm, and what if I want to build the ObjectId from other parts? I'm trying `.updateMany({ "_id": ObjectId('613bfe197524c621b9953012') }, [ { "$set": { "carnival": ObjectId({ "$substrBytes": [ "$_partition", 25, 24 ] }) } } ], {})' and getting "Argument passed in does not match the accepted types"… – Ian Bailey-Mortimer Feb 27 '22 at 01:55
  • @IanBailey-Mortimer docs say it takes a 12 digit hexadecimal string. i’m not sure you can execute any operations inside ObjectID(), but if you can it’ll have to result in a 12 digit hexadecimal string. looks like you are trying to do 24 bytes. – katy lavallee Feb 28 '22 at 02:20
  • Thanks, I ended up doing it by first extracting the bit of the string I needed into a separate new field, then filtering by those values to set the new ObjectId field. – Ian Bailey-Mortimer Mar 01 '22 at 02:14