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– joanolo2017年07月29日 11:10:36 +00:00Commented Jul 29, 2017 at 11:10
3 Answers 3
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)
You can use Change Streams which can track real-time changes in a database or collection and perform some task, like updating a document in another collection. Analogically, the functionality is similar to triggers in SQL databases.
Note that change streams can be used with replica-set and sharded clusters only. This feature is available since MongoDB (削除) v4.2 (削除ここまで) v3.6.
In the question scenario, the serverList
collection document can be updated with the current count of scripts
collection after an insert or delete operation.
Also, see Change Events.