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?
3 Answers
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.
2 Comments
tsinik
Thanks Andrew, but this is not what i'm looking for. I use Morphia as a POJO mapper, so i don't want to add irrelevant fields. in any way all javascript arrays have a length property. I'm wondering if there is a way to use it in a query.
Scott Hernandez
No, there is no way to do that; there is no support for sorting by a function nor is there a synthetic field which is the array length. That means for now you need to store a count if you want to embed it and sort on that. Be careful how you update it though.
OK I found it :-)
dataStore.find(MyClass.class).order("-inner_array.length").asList();
does the trick.
1 Comment
AlbertEngelB
I'm pretty sure this query doesn't actually work. It may execute without giving an error, but when I try something similar in the mongo shell, nothing is actually sorted.