I am trying to change the type of a field from within the mongo shell.
I am doing this...
db.meta.update(
{\'fields.properties.default\': { $type :
Starting Mongo 4.2, db.collection.update() can accept an aggregation pipeline, finally allowing the update of a field based on its own value:
// { a: "45", b: "x" }
// { a: 53, b: "y" }
db.collection.update(
{ a : { $type: 1 } },
[{ $set: { a: { $toString: "$a" } } }],
{ multi: true }
)
// { a: "45", b: "x" }
// { a: "53", b: "y" }
The first part { a : { $type: 1 } } is the match query:
"a" to string when its value is a double, this matches elements for which "a" is of type 1 (double)).The second part [{ $set: { a: { $toString: "$a" } } }] is the update aggregation pipeline:
Mongo 4.2) which in this case modifies a field."$set" the value of "a" to "$a" converted "$toString".Mongo 4.2 to reference the document itself when updating it: the new value for "a" is based on the existing value of "$a".Mongo 4.0.Don't forget { multi: true }, otherwise only the first matching document will be updated.
In case your cast isn't from double to string, you have the choice between different conversion operators introduced in Mongo 4.0 such as $toBool, $toInt, ...
And if there isn't a dedicated converter for your targeted type, you can replace { $toString: "$a" } with a $convert operation: { $convert: { input: "$a", to: 2 } } where the value for to can be found in this table:
db.collection.update(
{ a : { $type: 1 } },
[{ $set: { a: { $convert: { input: "$a", to: 2 } } } }],
{ multi: true }
)