Suppose you have a MongoDB collection and need to find documents where a certain field contains more than N elements. There are a few simple ways to handle this.

The most straightforward approach is to use the where‘keyword:glyphxmw2iodx4code0xTheupsideisthatitworksforgreaterthan1,lessthan3,exactlyequaltox,andsoon.Thedownsideisthattheexpressionafter‘where` keyword: glyphxmw2iodx4code0x The upside is that it works for greater than 1, less than 3, exactly equal to x, and so on. The downside is that the expression after `where is JavaScript, so it runs noticeably slower.

Another neat method is:

JavaScript
db.accommodations.find({'name.1': {$exists: true}})

This finds the document where there exists an item in name whose id is 1.

In theory, you could also use this approach for greater than, greater than or equal to, less than or equal to, equal to, etc. — you just need to combine conditions with $or. But the query gets more complicated, and it may not be any faster than the previous approach.

ref: