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

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


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.


I would avoid using commands directly on crontab, you probably have a directory /etc/cron.hourly and crontab already have calls to run all the scripts in the specific folders, in determined intervals, hourly, daily for example

Then, inside /etc/cron.hourly you can create a monitor.sh. You can set the execution privilege of this script with

chmod +x /etc/cron.hourly/monitor.sh

Them, you make a js code to retrieve the data, for example, mongoscript.js:

use yourdbdb.my_docs.count()

And you final monitor.sh will probably be something like

#!/bin/bashmongo mongoscript.js > output.jscurl http://countersrv.com/ID -d value=@output.js