Query for documents where array size is greater than 1
There's a more efficient way to do this in MongoDB 2.2+ now that you can use numeric array indexes (0 based) in query object keys.
// Find all docs that have at least two name array elements.
db.accommodations.find({'name.1': {$exists: true}})
You can support this query with an index that uses a partial filter expression (requires 3.2+):
// index for at least two name array elements
db.accommodations.createIndex(
{'name.1': 1},
{partialFilterExpression: {'name.1': {$exists: true}}}
);
Update:
For mongodb versions 2.2+ more efficient way to do this described by @JohnnyHK in another answer.
1.Using $where
db.accommodations.find( { $where: "this.name.length > 1" } );
But...
Javascript executes more slowly than the native operators listed on this page, but is very flexible. See the server-side processing page for more information.
2.Create extra field NamesArrayLength
, update it with names array length and then use in queries:
db.accommodations.find({"NamesArrayLength": {$gt: 1} });
It will be better solution, and will work much faster (you can create index on it).