Mongoexport引号问题踩坑

今天想按_id导出一些数据
发现find可以搜到但是mongoexport总是exported 0 records

文档关于mongoexport --query部分:
You must enclose the query document in single quotes ('{ ... }') to ensure that it does not interact with your shell environment.
必须用单引号扩起来query部分

The query must be in Extended JSON v2 format (either relaxed or canonical/strict mode), including enclosing the field names and operators in quotes:
query必须把列名和操作符都括起来。

实验如下,首先在库里确定导出条件无误:

> db.umaru.find({"_id":{"$in":['202110251025102500001','202110251025102500002']} })
--这里条件用的单引号
{ "_id" : "202110251025102500001", "name" : "test" }
{ "_id" : "202110251025102500002", "name" : "test" }
> db.umaru.find({"_id":{"$in":["202110251025102500001","202110251025102500002"]} })
--双引号
{ "_id" : "202110251025102500001", "name" : "test" }
{ "_id" : "202110251025102500002", "name" : "test" }

发现单双引号都能查出结果来,但是:

mongoexport -d umaru -c umaru -q '{"_id":{"$in":["202110251025102500001","202110251025102500002"]} }' --type json -o exp.json
2021-10-25T21:30:57.013+0800	connected to: mongodb://localhost/
2021-10-25T21:30:57.017+0800	exported 2 records

 mongoexport -d umaru -c umaru -q '{"_id":{"$in":['202110251025102500001','202110251025102500002']} }' --type json -o exp.json
2021-10-25T21:31:08.594+0800	connected to: mongodb://localhost/
2021-10-25T21:31:08.598+0800	exported 0 records --单引号的导不出来

mongoexport -d umaru -c umaru -q "{'name':'Tom' }" --type json -o exp.json --导不出来
mongoexport -d umaru -c umaru -q '{"name":"Tom" }' --type json -o exp.json --可以导出

本来只针对JS的规则去查,了解到js的单双括号同种括号不能交叉,第一个单引号会找下一个单引号。但奇怪的是,为什么这句不会被前两个单引号截断?而是正常执行但返回0record?

‘{"_id":{"$in":[‘202110251025102500001’,‘202110251025102500002’]} }’

后来醒悟,因为mongoexport是跑在linux shell里的,所以是按照linux的规则匹配单双引号,这里可以在shell中打印一下:

echo '{"_id":{"$in":['202110251025102500001','202110251025102500002']} }'
{"_id":{"$in":[202110251025102500001,202110251025102500002]} }"

这里引号用的linux的规则,再放到mongo中搜一下:

> db.umaru.find({"_id":{"$in":[202110251025102500001,202110251025102500002]} }) 
> -- got nothing 
> db.umaru.find({"_id":{"$in":['202110251025102500001','202110251025102500002']} })
{ "_id" : "202110251025102500001", "name" : "test" }
{ "_id" : "202110251025102500002", "name" : "test" }
> 

果不其然,不带单括号的没有匹配到数据。
在执行mongoexport的时候是在linux环境下执行的,在find的时候是在mongo的js shell环境下执行的,虽然后者能搜到,但是因为格式原因前者在导出时并没有匹配到数据。

所以导出还是按照文档说的,-q条件前后用单引号,中间双引号应该没什么问题。

另外发现一个JS单双引号奇怪的小例子:

"'hello'" === '"hello"'
false
 "hello" ==='hello'
true

附:
Mongoexport官方文档说明

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值