Update MongoDB document with string value of DBRef ID in the same document

59 views Asked by At

I'm attempting to extract and set the string value of a DBRef in one of my collections.

Given the following entry,

"thing" : DBRef("things", ObjectId("id-string-here"), "my-db")

The desired result is to have alongside it,

"thingString": "id-string-here"

I've attempted to use $set to achieve this, but am struggling to access the nested value,

db.myCollection.update({predicate}, {$set:{thingString:"$thing.id"}})

But this just sets the literal string "$thing.id".

Using $thing sets the DBRef itself, which defeats the whole purpose, but means that it does find the relevant field during the update.

I've attempted the following variations, but to no avail:

  • $thing._id
  • $thing.oid
  • $thing.$id
  • thing.$id
  • thing.$_id
  • thing.$oid

As well as wrapping the $set statement in array as in this similar issue, but in that case, $thing.$id errors out, saying FieldPath field names may not start with '$'., and when thing is not prefixed with $, nothing is updated.

db.myCollection.updateOne({predicate}, [{$set:{stringThing: "thing.$id" }}])

And based on the comments,

db.myCollection.updateOne({predicate}, [{$set:{ stringThing: { $toString: "$thing.$id" }}}])

I've also attempted the same variations as above there, but in that case, nothing is updated.

Given that I can find using { "thing.$id" : ObjectId("id-string-here") }, I assume it would be possible to also access it in $set somehow.

MongoDB server version: 4.2.24

0

There are 0 answers