2013-07-25 42 views
0

我是Mongodb的新手。其实我有成千上万的文件在不同的文件夹中。所有文件都包含json数据。有超过三千万个文件。所以我认为存储这些数据的最好方式是基于文档的数据库。我知道 Import more than 1 json file using mongoimport这个SO贴子。但是,接受的答案需要一个包含文件名的集合。我无法在一个集合中放入三千万个文件名...如何将多个JSON文件导入Mongodb?

如何将多个json文件导入到Windows环境下的Mongodb?

回答

1

您需要用自己喜欢的语言编写脚本来读取每个文件,JSON将其解码,然后将它们逐个插入到MongoDB中。在PHP中,这样的脚本将类似于:

<?php 
$f = glob("*.json"); 
$m = new MongoClient; 
$c = $m->myDb->myCollection; 

foreach ($f as $fileName) 
{ 
    $contents = json_decode(file_get_contents($fileName)); 
    $c->insert($contents); 
} 
?> 
0

您可以创建一个批处理脚本获取给定文件夹的所有JSON文件,然后导入到数据库:

@echo off 
for %%f in (*.json) do (
"mongoimport.exe" --jsonArray --db databasename --collection collectioname --file %%~nf.json) 

希望这帮助

1

对于任何寻找跨平台解决方案的人,我创建了一个小Perl脚本来做到这一点。它需要一个数据库和目录参数,并将它在目录中找到的任何.json文件导入到mongodb中。如果你不给它一个目录,它只是使用你当前所在的那个目录。我需要改进检查.json文件的正则表达式,并且我相信这可以用更少的代码来完成(I'一个新手Perl僧侣),但这个工程,我喜欢Perl ..所以,任何人发现这一点 - 享受。

#!/usr/bin/perl 
use strict; 
use warnings; 

#this is a script for enumerating over every json file in a folder and importing it into mongodb 

my ($database, $directoryPath) = @ARGV; 

if(! $database) { #check for required database argument 
    die "A database argument must be provided to the script. Ex: perl mongorestore.pl wasp"; 
} 

#if a directory path is not given in arguments, operate in the current directory. 
if(!$directoryPath) { 
    $directoryPath = '.'; 
} 

#open directory and import json files to mongo 
opendir my $dir, $directoryPath or die "Cannot open directory at path $directoryPath."; 
my @files = readdir $dir; 
importJSONToMongo(@files); 
closedir $dir; 

#subroutine that takes an array of json files and imports them to the given mongodb database 
sub importJSONToMongo { 
    foreach my $file (@_) { 
     if($file =~ /.json/) { #only import json files - need to make this regex better (it would match *.metadata.json and other extraneous files) 

     $file =~ /(^.+?)(?=\.)/; #capture the filename before the '.json' extension 
     system("mongoimport -d $database -c $1 --jsonArray --file $directoryPath/$1.json"); 
     } 
    } 
}