Count Array elements or store array size to seperate property

I have a collection that contains an array of documents.
Also, I have an API that does querying of that collection, and one of the initial filters is that array size must be greater than 0.
I must point out that this API is being called a lot, and performance and fast response are a big concern for me.

Initial idea is to add extra property where I will save the current size of array (every time array is being updated I recalculate array size and store it to that property). Of course, I would add an index to that property.

I need advice, should I go with my initial idea, or is it possible to add $size operator to filter
{ “my_array”:{ “$size” :{ “$gt”: 0 }}}
This second idea is actually calculating array size on the fly.

Again, pointing out that I need max performance fr this.

Regards,
Marko

Hi @Marko_Saravanja, hope you are doing well.
Considering that you want max performance for this API, and this seems like a case where write operations are significantly fewer than the read operations, I would highly recommend adding an extra property to store the size of the concerned array.

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha

1 Like

Thank you @SourabhBagrecha for reply. I will do as you have advised me to.
This brings me to my second question, that I couldn’t figure out by myself.

What is the way to update that property in a single trip to database.
Currently I fetch size of array by projecting it in first query, and when size value is fetched, i run another update statement to update it.
Can this be done in a single statement?

Thanks,
Marko

Hi @Marko_Saravanja, you’re welcome.
Sure, I would be more than happy to answer that.
Please note:

Starting in MongoDB 4.2, you can use the aggregation pipeline for update operations. With the update operations, the aggregation pipeline can consist of the following stages:

Therefore you can do something like this:

db.arrays.updateOne({}, [{ $set: { count: { $size: "$items" } } }]);

And this will update the count field in a single go(without the need to fetch the array size separately).

Learn more about how to use aggregation pipeline to update documents.

I hope this will help you.

In case you have any doubts, please feel free to reach out to us.

Thanks and Regards.
Sourabh Bagrecha

1 Like

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.