Quick Tip: How to $size up a MongoDB Array

in Querying, Quick Tip

Since MongoDB will allow you to store more than just string and int values but also things like arrays … from time to time you might need to know how many items are in an array in your document.

For example, say you have a hosting business and to make a good profit you need to sell at least three upgrades to each hosting client.

To make sure you market to the correct people you want to find all the clients with two upgrades (and get them to sign up for just one more.)

Your general document structure looks something like this:

 customer_name : "Sam Taylor",
 email : "sam@widgetxyz.com",
 upgrades: ["ssl", "diskspace 3", "RAM 5"]
 customer_name : "Kyle Lopez",
 email : "klopez@buymybikes.com",
 upgrades: ["diskspace 3", "RAM 5"]

To get all the clients that have two upgrades we’ll use the $size operator:

> db.clients.find( { upgrades : { $size: 2 } } );

Now you’ll get back all the documents that have two upgrades in the “upgrades” array (or in this example, the document for “Kyle Lopez”.)

What about a range?

Unfortunately the $size operator doesn’t support ranges (like getting all documents with 2 to 4 array values.) To do that you’d need to create your own separate field to keep track of the count and query on that field.