0
votes

I need to update a field of multiple collection documents. The field is a DBRef and I just need to change the $ref field value.

One of the documents is like this:

{ "_id" : { "$oid" : "50ab682bd3155502a75c7cf6"} , "codeId" : { "$ref" : "version" , "$id" : { "$oid" : "511cb7d5696bdbaf4c85ebb1"}}}

The final result I want is this:

{ "_id" : { "$oid" : "50ab682bd3155502a75c7cf6"} , "codeId" : { "$ref" : "code" , "$id" : { "$oid" : "511cb7d5696bdbaf4c85ebb1"}}}

I've tried it like this:

db.collection.update(
   {}, 
   {$set:{"codeId":{$ref:"code"}}},
   false,
   true
);

The problem is that the $id is lost (set as null)

{ "_id" : { "$oid" : "50ab682bd3155502a75c7cf6"} , "codeId" : { "$ref" : "code" , "$id" : { "$oid" : null}}}

How do I keep the $id?

Thanks

1

1 Answers

1
votes

You can use dot notation in order to update the nested document. Note that, whenever the dot notation is used, it should be put between quotes.

db.collection.update(
   {}, 
   { $set:{
       "codeId.$ref":"code"
     }
   },
   false,
   true
);

You can read more about Database References.