Realm Validation

Hi All

Is there a way to find all documents in A collection with a field of typeA and update/change this so that field is of typeB

something like

db.collection.updateMany({field: {$exists: true}, field: {isOfTypeA} }, {$set: {field : typeB } } )

Thanks in advance

Hey Barry, welcome to the forums! :wave:

To check if a field has a certain type you can use the $type query operator.

Updating the values once you’ve found them is just a bit trickier. Broadly you have two options:

  • Run the query, update the values to the new type in your code, and then run some database update operations to save the new values. This can definitely work but has a few pieces to juggle.

  • Use an aggregation pipeline to run the query and update the values in a single command. This is definitely the cleaner option so I recommend it! You’d use $type inside of a $match stage to find the documents and then you’d use $convert (or one of its shorthand helpers like $toInt) to do the actual conversion inside of a $project stage.

Hopefully this helps! Please let us know if you have any trouble :slight_smile:

1 Like