I have been looking at the docs and searching for videos on my problem, but I find nothing. I have a db called HPDASH where I have 2 collections, scripts and serverList. My problem is that I want to create a field for serverList that has the count() of the collection scripts.

I have tried this:
db.scripts.insert([{name: 'local_script'}, {name: 'qidsloader'}])
db.serverList.insert({script_count: db.scripts.count() })

The problem is that when I insert another record to scripts, the data on scripts_count stays as 2.

Is it possible to achieve this on MongoDB?

  • The short answer is no. Find the count whenever you need to use it. – joanolo Jul 29 '17 at 11:10

As you have noticed, MongoDB doesn't support naturally triggers. So, you need "programming skills" to do that functionality. You can use mongoTriggers, what can installed with mongo-triggers npm package.


A far more optimal solution exactly for this usecase would be use Redis to store the counts for the collection under a hashset while mongodb has the collection itself, this ensures your collection wont be locked for upserts, you can read more about this strategy HERE (Disclaimer: not my website)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.