christophmccann
christophmccann

Reputation: 4211

Ordering MongoDB collection by size of nested array

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.

Upvotes: 3

Views: 1401

Answers (1)

Andrew Orsich
Andrew Orsich

Reputation: 53685

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.

Upvotes: 5

Related Questions