Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query mongodb from command line and send the result as HTTP request in crontab

I want to incorporate a simple monitoring into my application so I need to send an HTTP request that contains the number of documents in the mongodb collection from the crontab.

The requests are described on the page http://countersrv.com/ as follows:

curl http://countersrv.com/ID -d value=1

I need to query the mongodb from the command line and get the number of documents in the collection. It should be something like db.my_docs.count().

I want to send this number every hour so need to add something like this into crontab:

0 * * * * curl http://countersrv.com/ID -d value=...query mongo here...?
like image 307
Alex Netkachov Avatar asked Dec 09 '22 07:12

Alex Netkachov


1 Answers

Not meaning to detract from the timely answer given by Victor, but the "one liner" form of this would be:

 mongo --quiet --eval 'var db = db.getSiblingDB("database"); print( "value=" + db.collection.count() );' | curl -X POST http://countersrv.com/[edit endpoint] -d @-

The --quiet suppresses the startup message on the shell and --eval alows the commands to pass through on the command line.

To select the database you use .getSiblingDB() as the method helper for the interactive shell use database with the "database" name you want. After this either just the "collection" name or .getCollection() method can be used along with the basic function.

Simply print() the "key/value" pair required and pipe to curl at the "edit endpoint" for countersrv, which is the default viewing page. The @- construct takes stdin.

like image 89
Neil Lunn Avatar answered Dec 17 '22 22:12

Neil Lunn