在mongodbs windows cli中使用单个命令进行mongodb查询

时间:2017-09-01 08:29:24

标签: windows mongodb command-line-interface

我尝试在单个命令中执行mongodb查询,以便从Windows软件中运行批处理脚本。 mongodb数据库已经构建,这是我的Windows控制台命令和cli查询工作:

C:\Program Files\MongoDB\Server\3.0\bin>mongo ds045565-a1.mongolab.com:45565/heroku_mydatabase
2017-09-01T09:14:05.196+0100 I CONTROL  Hotfix KB2731284 or later update is not installed, will zero-out data files
MongoDB shell version: 3.0.7
connecting to: ds045565-a1.mongolab.com:45565/heroku_mydatabase
rs-ds045565:PRIMARY> db.auth("myusername","mypassword");db.getCollection('94081_DS_FuelNBS').find({})
{ "_id" : ObjectId("58ab4ae3bc5cf82663236b4f"), "code" : "D", "description" : "Diesel", "lastModified" : ISODate("2017-02-20T20:00:35.680Z") }
{ "_id" : ObjectId("58ab4ae3bc5cf82663236b50"), "code" : "H", "description" : "Hydrogen", "lastModified" : ISODate("2017-02-20T20:00:35.680Z") }
{ "_id" : ObjectId("58ab4ae3bc5cf82663236b51"), "code" : "P", "description" : "Petrol", "lastModified" : ISODate("2017-02-20T20:00:35.680Z") }
rs-ds045565:PRIMARY> exit
bye

如果我然后尝试作为单个Windows命令执行,除了错误消息之外我没有得到任何响应输出:

C:\Program Files\MongoDB\Server\3.0\bin>mongo ds045565-a1.mongolab.com:45565/heroku_mydatabase mymongodbcommands.txt > output.txt

C:\ Program Files \ MongoDB \ Server \ 3.0 \ bin>

以下是mymongodbcommands.txt和output.txt

的内容

mymongodbcommands.txt:

db.auth("myusername","mypassword");db.getCollection('94081_DS_FuelNBS').find({})

output.txt的

2017-09-01T09:15:41.604+0100 I CONTROL  Hotfix KB2731284 or later update is not installed, will zero-out data files
MongoDB shell version: 3.0.7
connecting to: ds045565-a1.mongolab.com:45565/heroku_mydatabase

1 个答案:

答案 0 :(得分:0)

请考虑Scripts for Mongo Shell - 这是做你想做的正确方法

以您的案例为例:

mongo ds045565-a1.mongolab.com:45565/heroku_mydatabase -u myusername -p mypassword --eval "var c = db.getCollection('94081_DS_FuelNBS').find(); while(c.hasNext()) {printjson(c.next())}"

您可以进一步构建自己的mymongodbcommands.js并将其传递给:

mongo host:port/db mymongodbcommands.js > output.txt

而js文件将包含身份验证和所需的一组命令

另请参阅thisthat类似问题的答案。