Count children object, what is the best approach?


For an futur project I need to count children of an object.

I have an object A with children of type B and C. I would count the child number on type B and C, I see 3 methods

method 1 : use a views

method 2 : add a values in object A to store children number. But I need to update the A with CAS method (to ensure database consistency ) when I add/remove an child.

method 3 : add a new document (one by child type) to save number and use atomic method incr and decr when I add/remove an child. But with this method like all key must be in RAM, I need more memory on server.

What is the best approach for my problem ? 1, 2, 3 or other ?


1 Answer

« Back to question.

Hello Xavier,

As often the correct answer will be "it depends"... but this does not help you that much.

I will give you my point of view...

My favorite will be to use a view with something like:

  emit([doc.parent_id, doc.type]);

and use the _count reduce

With this you can then count the number of children for each parent, and also by type.

For example:
- count children for parent:1 document:


- count children for parent:1 by type:


So this is for me the simplest way, since it does not have any impact on your set operation.

Also, in addition to the other approaches you have described you can also:
- list the keys (and even more) of the children in an array in the parent and count this. (you will have the same constraints regarding the consistency management)

- embed the children in the document (I guess that if you have not mentioned it, it is because it is not compatible with your use case but may be interesting to say it this response)


Thank you very much.

I have not mentioned the method "embed the children in document", because in some case the number of child can be over 500

Best regards