1

在我的 mongo 数据库中,我有这种格式的数据

{ "_id" : { "$oid" : "53179b7f036457ea7fff00a7" }, "act" : "browserInfo", "creAt" : { "$date" : "2014-03-05T16:47:43.845-0500" }}

我正在尝试提出一个 shell 脚本,该脚本将使用以下脚本导出具有给定日期范围的条目(我将其命名为 csv_from_mongo_collection.sh)

#!/bin/bash
db_name=$1
collection=$2
output_file=$3

for i in "$@"
do
case $i in
    --from=*)
    from="${i#*=}"
    shift
    ;;
    --to=*)
    to="${i#*=}"
    shift
    ;;
esac
done

query="{creAt:{$gte:new Date($from),$lt:new Date($to)}}";

mongoexport --db "$db_name" --collection "$collection" --out "$output_file" --query "$query"

当我运行以下命令时,我看到该指定集合中的所有条目都已上传,而忽略了我设置的日期范围。

csv_from_mongo_collection.sh mydb analytics analytics_content.json --from=01/01/2013 --to=12/01/2013

有人可以帮助修复我的脚本/命令吗?谢谢

4

2 回答 2

0

问题在query="{creAt:{$gte:new Date($from),$lt:new Date($to)}}";

如何$gte以及$lt将如何治疗?作为未定义的变量?($from 已定义):)

new Date("01/01/2013")正确但不正确new Date(01/01/2013)

根据需要使用单引号'生成查询文档。

于 2014-09-09T02:58:30.370 回答
0

通过使用双引号 ( ") 创建查询,查询字符串中前缀为 的所有单词都$将被评估为变量。因为$word是 bash 变量。我在您的查询字符串中标记了所有变量:

query="{creAt:{$gte:new Date($from),$lt:new Date($to)}}";
               ^^^^          ^^^^^  ^^^          ^^^

$from正如您所看到的,和不仅$to是变量,而且$gte$lt被评估为变量!那么如何在符合查询语法的同时将日期存储在字符串中?

使用转义字符\转义\$查询字符串中的 。现在$签名不会被评估为变量的使用!下面的例子。

query="{creAt:{\$gte:new Date($from),\$lt:new Date($to)}}";
于 2020-04-03T13:20:31.110 回答