Casting fields in MongoDB Docs

So you have your document schema sorted but your application is throwing in mixed types on an indexed field. Not the end of the world, but your indexes are performing sub optimally.

16 July 2013 • 3 min read


Hit up your MongoShell:

	$eval : db.COLLECTION_NAME.find({
			$exists : true,
			$type : 2
	}).forEach( function(obj) {
		obj.FIELD_NAME = new NumberInt(obj.FIELD_NAME);;
	nolock: true

All types have a numeric identifier and a full list can be seen here.

Much quicker than processing type operators on the application side. However, large collections will lock the database so your mileage will vary!

Published on 16 July 2013


Other content you may be interested in....

If you use the internet, it's probably a good idea to reset your passwords. Don't say you haven't been warned.

4 min read

security ssl

Using NGINX as a load balancer can be great. Monitoring upload progress to feed back to your user doesn't come out the box.

2 min read


bodged with ♥ in NCL, AMS, NAP, NYC, BOS and LDN