需求
在寫小工具的時候,經常遇到需要從mongodb 里面查東西來用,因為要跟其他bash 工具鏈結合在一起用,所以最理想的方法是能夠在shell 上執行查詢,然后pipe 給接下來的工具做處理。
方案
幸運的是對於mongo 來說做起來是很方便的,只需要使用mongo --eval 即可。例1:
mongo 192.168.1.2:27060/mybase --eval 'printjson(db.tasks.findOne())'
這段腳本首先鏈接上地址為192.168.1.2:27060 的mongodb 服務器,然后在mybase 數據庫下執行后面引號內的javascript,這段javascript 和mongoshell 里的並沒有區別。值得注意的是這里是用的mongoshell 的一個全局函數 printjson 用來把查詢結果轉換成json 打印出來。
例2:
mongo 192.168.1.2:27060/mybase --eval 'db.tasks.find({type:"danger"}).forEach(printjson)'
在查詢結果不唯一的時候,即不像例1那樣使用findOne 返回單一結果,而是返回一個“結果集” 的時候,mongo 實際上返回的是一個可遍歷的cursor,這時候如果你用printjson 把查詢語句包起來printjson(db.find()...) 的話,實際打印出的是cursor 的內容。正確的做法是forEach 遍歷cursor 然后打印每一項。
例3:
mongo 192.168.1.2:27060/mybase --eval 'db.tasks.find({type:"danger"}).forEach(function(e){print(e._id.str)})'
找出所有屬性為“danger” 的task 的id,這里使用ObjectID的str 屬性來把他轉換成字符串。
總結
注意返回內容,一般是一個可遍歷的cursor。
參考:
http://stackoverflow.com/questions/4837673/how-to-execute-mongo-commands-through-shell-scripts