【发布时间】:2019-09-17 15:14:34
【问题描述】:
我最近开始学习 MongoDB。今天老师教我们mongoexport命令。在练习相同的过程中,我遇到了一个典型的问题,包括教练在内的其他同伙都没有遇到过。我在我的 Windows 10 机器上使用 MongoDB 版本 4.2.0。
如果我对我的集合使用 mongoexport 而不使用任何 -q 参数来指定任何过滤条件,它就可以正常工作。
mongoexport -d trainingdb -c employee -f empId,name,designation -o \mongoexport\all-employees.json
2019-09-17T18:00:30.300+0530 connected to: mongodb://localhost/
2019-09-17T18:00:30.314+0530 exported 3 records
但是,每当我将 JSON 查询指定为 -q(或 --query)时,它都会给出如下错误。
mongoexport -d trainingdb -c employee -f empId,name,designation -q {'designation':'Developer'} -o \mongoexport\developers.json
2019-09-17T18:01:45.381+0530 connected to: mongodb://localhost/
2019-09-17T18:01:45.390+0530 Failed: error parsing query as Extended JSON: invalid JSON input
在我为查询尝试的所有不同风格中,同样的错误仍然存在。
-q {'designation':'Developer'}
--query {'designation':'Developer'}
-q "{'designation':'Developer'}"
我什至尝试在 'empId' 上使用不同的查询条件作为 -q {'empId':'1001'} 但没有运气。我不断收到同样的错误。
根据one of the suggestions given in the StackOverflow website,我尝试了以下选项,但得到了不同的错误。
-q '{"designation":"Developer"}'
错误是:'query '[39 123 101 109 112 73 100 58 49 48 48 49 125 39]' 是无效的 JSON:json: cannot unmarshal string into Go value of type map[string]interface {}'。
2019-09-17T20:24:58.878+0530 query '[39 123 101 109 112 73 100 58 49 48 48 49 125 39]' is not valid JSON: json: cannot unmarshal string into Go value of type map[string]interface {}
2019-09-17T20:24:58.882+0530 try 'mongoexport --help' for more information
我真的不确定这里缺少什么?尝试了一些谷歌搜索,也通过了官方MongoDB documentation of the mongoexport - 但没有运气。
我系统中的员工集合如下所示,包含 3 个文档。
> db.employee.find().pretty()
{
"_id" : ObjectId("5d80d1ae0d4d526a42fd95ad"),
"empId" : 1001,
"name" : "Raghavan",
"designation" : "Developer"
}
{
"_id" : ObjectId("5d80d1b20d4d526a42fd95ae"),
"empId" : 1002,
"name" : "Kannan",
"designation" : "Architect"
}
{
"_id" : ObjectId("5d80d1b40d4d526a42fd95af"),
"empId" : 1003,
"name" : "Sathish",
"designation" : "Developer"
}
>
更新
按照@NikosM 的建议,我已将查询保存在 .json 文件 (query.json) 中,并使用新方法尝试了相同的 mongoexport 命令。尽管如此,还是没有运气。同样的元帅错误。
cat query.json
{"designation":"Developer"}
mongoexport -d trainingdb -c employee -f empId,name,designation -q 'query.json' -o \mongoexport\developers.json
2019-09-17T21:16:32.849+0530 query '[39 113 117 101 114 121 46 106 115 111 110 39]' is not valid JSON: json: cannot unmarshal string into Go value of type map[string]interface {}
2019-09-17T21:16:32.852+0530 try 'mongoexport --help' for more information
对此的任何帮助将不胜感激。
【问题讨论】:
-
当然
{'designation':'Developer'}不是有效的 json,因为没有单引号是有效的 json。因此,需要对 json 中的字符串使用双引号。然后尝试解决其他错误(可能是特定于操作系统而不是特定于 MongoDB)。否则只需使用文件来包含 json,而不是字面意思 -
请在问题中添加示例员工文档
-
用双引号试试同样的方法:
-q "{\"designation\":\"Developer\"}" -
显然发生这种情况是因为在 Windows 中,您必须将查询放在双引号之间。因此,您必须在查询中添加转义双引号,以使其成为有效的 JSON
-
@Caconde,你真可爱 :) 感谢您的大力支持。我很感激。
标签: json mongodb mongoexport json-query