toObjectId

open fun <R : Any> Value<R, *>.toObjectId(): Value<R, <Error class: unknown class>>(source)

Converts this value to an ObjectId.

Conversion algorithm

BsonType.ObjectId is returned as itself.

BsonType.String is parsed as an ObjectId as a 24-character hexadecimal representation, for example "5ab9cbfa31c2ab715d42129e".

BsonType.Null always returns null.

Other types throw an exception.

Example

class Product(
val _id: ObjectId,
)

// Migrate ids which were accidentally written as strings:
products.updateManyWithPipeline {
_id set of(Product::_id).toObjectId()
}

External resources

See also

Get the value's type.