Ale*_*hov 4 bash monitoring crontab mongodb
我想在我的应用程序中加入一个简单的监视器,因此我需要发送一个HTTP请求,其中包含来自crontab的mongodb集合中的文档数.
这些请求在http://countersrv.com/页面上描述如下:
curl http://countersrv.com/ID -d value=1
Run Code Online (Sandbox Code Playgroud)
我需要从命令行查询mongodb并获取集合中的文档数.应该是这样的db.my_docs.count().
我想每小时发送一个这个号码,所以需要在crontab中添加这样的内容:
0 * * * * curl http://countersrv.com/ID -d value=...query mongo here...?
Run Code Online (Sandbox Code Playgroud)
避免直接在crontab上使用命令,你可能有一个目录/etc/cron.hourly和crontab已经调用以确定的间隔,每小时,每天运行特定文件夹中的所有脚本,例如
然后,在/etc/cron.hourly中你可以创建一个monitor.sh,用它设置这个脚本的执行权限
chmod +x /etc/cron.hourly/monitor.sh
Run Code Online (Sandbox Code Playgroud)
使用必要的代码创建一个脚本来检索数据,例如,mongoscript.js:
use yourdb
db.my_docs.count()
Run Code Online (Sandbox Code Playgroud)
脚本可能会像
#!/bin/bash
mongo mongoscript.js > output.js
curl http://countersrv.com/ID -d value=@output.js
Run Code Online (Sandbox Code Playgroud)
并不意味着减损Victor给出的及时答案,但这种形式的"单线"形式将是:
mongo --quiet --eval 'var db = db.getSiblingDB("database"); print( "value=" + db.collection.count() );' | curl -X POST http://countersrv.com/[edit endpoint] -d @-
Run Code Online (Sandbox Code Playgroud)
的--quiet抑制外壳上的启动消息和--evalalows的命令在命令行上通过.
要选择数据库,请将其.getSiblingDB()用作交互式shell的方法助手,并use database使用所需的"数据库"名称.在此之后,只要"集合"名称或.getCollection()方法可以与基本功能一起使用.
只print()需要"键/值"对,并curl在counterrv的"编辑终点"处进行管道处理,这是默认的查看页面.该@-构造需要stdin.