3

Is it possible to order a MongoDB collection by the size of a nested array? Say for example we have a collection of Question documents and each document has a nested array of answers. I want to be able to sort the collection and pull out the most answered questions? I have been looking around and I am not sure its doable directly from MongoDB and I think it would be quite performance intensive to extract all questions and then sort them in Java.

1 Answer 1

5

You cann't query by size of nested collection, you need to create field with size of collection for such needs(mongo db documentation):

The $size operator matches any array with the specified number of elements. The following example would match the object {a:["foo"]}, since that array has just one element:

db.things.find( { a : { $size: 1 } } );

You cannot use $size to find a range of sizes (for example: arrays with more than 1 element). If you need to query for a range, create an extra size field that you increment when you add elements.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.