使用 mongoimport 在 MongoDB 中将 CSV 数据作为数组导入

发布于

MongoDB的导入实用程序引入了一个新参数,允许您将CSV数据作为数组导入。mongoimport

导入 CSV 或 TSV 文件时,该参数将字段中的自然数解释为数组索引。--useArrayIndexFields

例

假设我们有一个名为 CSV 文件,如下所示:tags.csv

tags.0,tags.1,tags.2,tags.3
html,css,sql,xml

我们可以使用参数导入它,这将导致将列标题中的数字解释为数组索引。--useArrayIndexFields``mongoimport

例:

mongoimport --db=krankykranes --type=csv --headerline --useArrayIndexFields --file=tags.csv

输出:

2021-01-03T20:55:44.284+1000 no collection specified 2021-01-03T20:55:44.284+1000 using filename ’tags’ as collection 2021-01-03T20:55:44.297+1000 connected to: mongodb://localhost/ 2021-01-03T20:55:44.330+1000 1 document(s) imported successfully. 0 document(s) failed to import.

看到我没有指定集合名称,它创建了一个名为(基于文件名)的集合,然后导入了我的文档。tags

让我们跳到蒙戈外壳并检查集合。

db.tags.find()

结果:

{ “_id” : ObjectId(“5ff1a2b0300ed79d9836882f”), “tags” : [ “html”, “css”, “sql”, “xml” ] }

我们可以看到 CSV 数据已作为 JSON 数组导入。

这里又是,但格式更好,这可能会使数组更容易看到。

db.tags.find().pretty()

结果:

{ “_id” : ObjectId(“5ff1a2b0300ed79d9836882f”), “tags” : [ “html”, “css”, “sql”, “xml” ] }

与其他 CSV 数据相结合

上一示例中的 CSV 文件仅包含数组数据。但是我们也可以在文件中包含其他数据。

下面是一个包含其他数据的 CSV 文件示例。articles.csv

_id,title,body,tags.0,tags.1,tags.2,tags.3 1.0,Web,blah,html,css,sql,xml 2.0,Animals,blah 2,cats,dogs 3.0,Plants,blah 3,trees 4.0,Oceans,blah 4

让我们导入该文件:

mongoimport --db=krankykranes --type=csv --headerline --useArrayIndexFields --file=articles.csv

输出:

2021-01-03T21:14:38.286+1000 no collection specified 2021-01-03T21:14:38.287+1000 using filename ‘articles’ as collection 2021-01-03T21:14:38.336+1000 connected to: mongodb://localhost/ 2021-01-03T21:14:38.407+1000 4 document(s) imported successfully. 0 document(s) failed to import.

现在让我们跳到 mongo shell 并检查集合。

db.articles.find()

结果:

{ “_id” : 1, “title” : “Web”, “body” : “blah”, “tags” : [ “html”, “css”, “sql”, “xml” ] } { “_id” : 3, “title” : “Plants”, “body” : “blah 3”, “tags” : [ “trees” ] } { “_id” : 4, “title” : “Oceans”, “body” : “blah 4” } { “_id” : 2, “title” : “Animals”, “body” : “blah 2”, “tags” : [ “cats”, “dogs” ] }

让我们把它美化一点。

db.articles.find().pretty()

结果:

{ “_id” : 1, “title” : “Web”, “body” : “blah”, “tags” : [ “html”, “css”, “sql”, “xml” ] } { “_id” : 3, “title” : “Plants”, “body” : “blah 3”, “tags” : [ “trees” ] } { “_id” : 4, “title” : “Oceans”, “body” : “blah 4” } { “_id” : 2, “title” : “Animals”, “body” : “blah 2”, “tags” : [ “cats”, “dogs” ] }

因此,我们可以看到文档已被创建为完美的JSON/BSON文档,并且已经为相关数据创建了数组。

请注意,尚未为文档 4 创建任何数组。这是因为 CSV 文件中未提供数组数据。因此,它没有创建具有空数组的字段,而是没有创建字段或数组。