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
先总结到这吧。