Dor
Dor

Reputation: 902

How to annotate the result documents with a count of child documents?

I have a collection of categories, each category document containing a link to its parent (except the root categories). Pretty simple so far.

I want to list the categories, and add a subcategory_count field to every document with the count of direct descendants.

How should I go about doing this? Could Map/Reduce be of use?

Upvotes: 0

Views: 214

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230306

There are no "calculated columns" in MongoDB, so you can't select data and count subdocuments at the same time.

This is also the reason why most people store array length along with the array.

{friends_list: [1, 3, 234, 555],
 friends_count: 4}

This helps for easier retrieval, filtering, sorting, etc. But it requires a little bit more of manual work.

So, you are basically limited to these options:

  1. Store everything in one document.

  2. Store subcategory count in the category.

  3. Count subcategories on the client-side.

Upvotes: 1

milan
milan

Reputation: 12402

find() to get all of them, count the number of subcategories on each level and then update().

But it seems like your domain object should be doing this for you, so you end up with one category object that can contain categories (which could also contain categories...), and hence one mongodb document (you're listing all of them anyway, so it makes sense to retrive the whole thing in one query).

Upvotes: 0

Related Questions