Suppose I have:
Order: {_id: ..., items: [...]}
How to filter orders which have item number greater than 5?
You can use the $where operator.
> db.orders.save({Order: {items: [1,2]}})
> db.orders.save({Order: {items: [1,2,3]}})
> db.orders.find({$where:function() { if (this["Order"]["items"].length > 2) return true; }})
{ "_id" : ObjectId("4d334c9102bcfe450ce52585"), "Order" : { "items" : [ 1, 2, 3 ] } }
Two downsides of $where are that it can't use an index and the BSON object must be converted to a JavaScript object, since you are running a custom JavaScript function on every document in the collection.
So, $where can be very slow for large collections. But, for ad hoc or rarely run queries, it's extremely handy. If you frequently need to run queries like this, then you should follow Bugai13's recommendation, since you can then index the key in which you store the array size.