How can I sort MongoDB query results by inner array size?

tsinik picture tsinik · Apr 23, 2011 · Viewed 7.9k times · Source

I'm using Morphia to access mongoDB. I need to get a list of objects by the length of the inner array. Does any one have an idea how it can be done without getting all the collection to Java and sort it there?

Answer

Andrew Orsich picture Andrew Orsich · Apr 23, 2011

You should create extra field with nested array size and use $inc to update this field.

Also you can use $where , but it very slow.

You search by nested array length like this:

db.coll.find({ $where: "this.nestedArray.length > 3" });

But as i said better to create an extra field.