mongodb和shell脚本交互

linux,经常要使用shell脚本写一些mongodb的简单操作,我总结了工作中经常用的几个方法。

先看第一个例子:

#file是文件名
#使用EOF
#库:test_db
#表:test_table
cat file|while read line
do
./mongo -port 20000 test_db <<EOF
db.test_table.find({_id:/$line/})
EOF
done

上述例子中,两个EOF之间的语句,不能有空格,tab等,直接顶格写命令。

EOF
#下面的语句顶格写
db.test_table.find({_id:/$line/})
EOF

再看第二个例子:这个例子也是使用EOF之间写mongo命令,下面的例子主要说明mongodb命令如何使用shell中的变量,即例子中的变量result和变量line

其中库名:test_db, 表名:atable

cat 500test1.txt |while read line;
do
    echo $line
    result=grep -w "001_${line}" /tmp/testa.json
    echo $result
~/sbin/mongodb/mongo --host 10.12.214.15 --port=20000 test_db << EOF
db.atable.insert($result)
db.atable.find({id:"001$line "})
exit
EOF
done;

再看第三个例子:稍微复杂点的例子,主要是说明打印函数,方便调试脚本

#!/bin/bash
user=${1}
size=$2
color=$3

${HOME}/bin/mongo 10.1.17.42:10000/test_db <<EOF
var rec_count=db.table_a.count({"user":"${user}", "size":"${size}"});
//print(eval(rec_count));
print("check ${user} ${color} ${size}")
if(rec_count > 0){
var dedup_count=db.dedup_id.count({"user":"${user}", "size":"${size}"});
//print(dedup_count);
if(dedup_count > 0){
print("${user} ${color} ${size}"+" dedup found");
}else{
print("${user} ${color} ${size}"+" dedup not found");
db.dedup_id.insert({ "size" : "${size}", "color" : "${color}", "user" : "${user}"});
print("insert OK")
}
}else{
print("${user} ${color} ${size}"+" index not found");
}
print("abc")
EOF

第四个例子,这个例子主要说明,find出来的json数据如何解析,并打印

HOME=/home/test/sbin/mongodb/
$HOME/mongo --port 30000 test_db <<EOF
var col=db.atable.findOne({msg:"$1", _id:"$2"})
print(col.msg+" "+col.size+" "+col.user+" $1 "+"$2")
exit
EOF

先总结到这吧。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值