Mongoexport 尝试导出超过 120 天的条目,shell 变量不起作用

问题描述

我制作了一个 shell 脚本,我试图从我的数据库中导出超过 1 天的条目。我的数据库一个名为“problemDate”的字段,其中包含 yyyy-mm-dd 格式的字符串格式的日期,例如 (2021-03-22)

mongoexport --host localhost --db pagesuccess --collection problem -q='{ "problemDate": { "$lte" : "2021-03-22"}} ' --type=csv --out text2.csv --fields date,problemDetails,problem,tags,url,language,institution,section,theme
  connected to: mongodb://localhost/
  exported 8 records
--------------------------------------------------------------------------------------------------------------------
older1Day=$(gdate --date="1 days ago" +%F)
mongoexport --host localhost --db pagesuccess --collection problem -q='{ "problemDate": { "$lte" : "$older1Day"}} ' --type=csv --out text2.csv --fields date,theme
  connected to: mongodb://localhost/
  exported 0 records

我真的不确定为什么第二个不起作用但第一个起作用。唯一的区别是我在第二个命令中使用了日期变量。我真的很好奇为什么第二个不起作用。

解决方法

如果不将变量放在双引号而不是单引号中,它们将不会被扩展。因此该命令需要重写为:

mongoexport --host localhost --db pagesuccess --collection problem -q="{ \"problemDate\": { \"$lte\" : \"$older1Day\"}}" --type=csv --out text2.csv --fields date,problemDetails,problem,tags,url,language,institution,section,theme
,

问题是因为我使用了单引号。在 Bash 中,您不能像使用双引号那样在单引号中插入变量。

效果很好:

older120Days=$(gdate --date="1 days ago" +%F)
mongoexport --host localhost --db pagesuccess --collection problem -q='{ "problemDate": { "$lte" : "'"$older120Days"'"}} ' --type=csv --out text2.csv --fields date,theme