2

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?

asked Jul 28, 2017 at 21:13
1
  • The short answer is no. Find the count whenever you need to use it. Commented Jul 29, 2017 at 11:10

3 Answers 3

0

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.

answered Jul 29, 2017 at 6:47
0
0

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)

answered Mar 3, 2018 at 7:37
0

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.

answered Jan 24, 2024 at 7:44

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.