【问题标题】:Issue in executing mongo commands through shell script通过 shell 脚本执行 mongo 命令的问题
【发布时间】:2018-08-07 21:50:01
【问题描述】:

根据 Matt 对here 提出的问题的回答:

我试过下面的脚本

use sample

db.testCollection.insert({"result":1})

但是,当我按照建议运行时,出现如下错误,并且记录被插入到默认数据库的集合中,而不是按预期插入到“样本”数据库中。

[tmp]# mongo < output.js
connecting to: mongodb://127.0.0.1:27017
2018-03-21T14:54:52.713+0530 E QUERY    [thread1] SyntaxError: unterminated string literal @(shellhelp2):1:21
WriteResult({ "nInserted" : 1 })
bye

请寻求帮助。

【问题讨论】:

  • 尝试使用db.'testCollection'.insert({"result":1})
  • 这不起作用,给出了不同的错误
  • 试试这个 db.getCollection(testCollection).insert({"result":1})

标签: mongodb


【解决方案1】:

您的脚本和命令是正确的。
在 Unix 上,如果您的脚本具有 Dos/Windows 行尾 (CRLF) 而不是 Unix 行尾 (LF),您将收到此错误。

要转换你的行尾:

dos2unix output.js

或:How to convert DOS/Windows newline (CRLF) to Unix newline (LF) in a Bash script?

【讨论】:

    【解决方案2】:

    您需要指定数据库名称,如下所示。

    mongo your-db-name < output.js
    

    【讨论】:

      最近更新 更多