如何将csv文件导入Mongo?

问题描述 投票:0回答:1

我想将 csv 文件导入 MongoDB。 我发现有一个命令“mongoimport”可以导入文件。

基于 mongoimport 文档 我已经安装了 Windows数据库工具

我把环境变量的PATH设置为:

C:\Program Files\MongoDB\Tools\100\bin

然后我重新启动了电脑。

我创建了一个 bash 脚本来将所有 csv 文件执行 mongoimport 到脚本目录中:

#!/bin/bash

HOST="00.00.000.00:00000"                                                                                                             
USERNAME="user"
PASSWORD="password"
DB_NAME="mydb"

CSV_EXTENSION=".csv"

# Get the directory path of the script
SCRIPT_DIRECTORY=$(pwd)

for fullFilePath in "$SCRIPT_DIRECTORY"/*
do
  
  filename="${fullFilePath##*/}"                                  
  
  fileNameWithoutExtension="${filename%.[^.]*}"                   

  fileExtension="${filename:${#fileNameWithoutExtension}}"        

  fileExtensionLowerCase=${fileExtension,,}
  
  if [ "$fileExtensionLowerCase" == "$CSV_EXTENSION" ]; then
  
      echo "importing collection: $fileNameWithoutExtension ..."
      
      mongoimport --db=$DB_NAME --collection=$fileNameWithoutExtension --type csv --headerline --file=$fullFilePath --host=$HOST -u=$USERNAME -p=$PASSWORD --authenticationDatabase=admin
  fi
  
done

当我执行我得到的脚本时

$ ./Import_File_On_Mongo.sh
importing collection: Test ...
2023-10-06T17:49:03.612+0200    error parsing command line options: error parsing positional arguments: provide only one file name and only one MongoDB connection string. Connection strings must begin with mongodb:// or mongodb+srv:// schemes
mongodb bash shell mongo-shell mongoimport
1个回答
0
投票

错误是变量上缺少双引号(如 @LMC 在评论中提到的)。

然后我添加了身份验证机制,因为我使用的是 SCRAM-SHA-256,默认的是 SCRAM-SHA-1。

#!/bin/bash

HOST="00.00.000.00:00000"                                                                                                             
USERNAME="user"
PASSWORD="password"
DB_NAME="mydb"

CSV_EXTENSION=".csv"

# Get the directory path of the script
SCRIPT_DIRECTORY="$(pwd)"

for fullFilePath in "$SCRIPT_DIRECTORY"/*
do
  
  fileName="${fullFilePath##*/}"
  
  fileNameWithoutExtension="${fileName%.[^.]*}"
  
  fileExtension="${fileName:${#fileNameWithoutExtension}}"
  fileExtensionLowerCase="${fileExtension,,}"
  
  if [ "$fileExtensionLowerCase" == "$CSV_EXTENSION" ]; then
  
      echo "importing collection: $fileNameWithoutExtension ..."
      
      mongoimport --file="$fullFilePath" --type csv --headerline --db="$DB_NAME" --collection="$fileNameWithoutExtension" --host="$HOST" -u="$USERNAME" -p="$PASSWORD" --authenticationMechanism SCRAM-SHA-256 --authenticationDatabase bnl-mongodb
  fi
  
done
© www.soinside.com 2019 - 2024. All rights reserved.