Sco*_*McG 6 csv mongodb mongoimport
我正在尝试使用 mongoimport 从 CSV 导入到 mongodb 3.4,并且我希望将空列作为字段的空值导入。
mongoimport 文档给我的印象是,如果未指定 --ignoreBlanks,我将得到我想要的行为。
--忽略空白
Run Code Online (Sandbox Code Playgroud)Ignores empty fields in csv and tsv exports. If not specified, mongoimport creates fields without values in imported documents.
但是,当我尝试在不使用 --ignoreblanks 的情况下加载此示例数据时:
field_1.string(),field_2.int32(),field_3.string()
A,5,B
C,,D
E,7,F
Run Code Online (Sandbox Code Playgroud)
然后我在任何不是字符串的字段上收到错误。
mongoimport --collection null_test --type csv --headerline --columnsHaveTypes --file null_test.csv --verbose
2017-08-08T16:55:42.989+0000 filesize: 67 bytes
2017-08-08T16:55:42.989+0000 using fields: field_1,field_2,field_3
2017-08-08T16:55:43.001+0000 connected to: localhost:27017
2017-08-08T16:55:43.001+0000 ns: DEV.null_test
2017-08-08T16:55:43.001+0000 connected to node type: standalone
2017-08-08T16:55:43.001+0000 using write concern: w='1', j=false, fsync=false, wtimeout=0
2017-08-08T16:55:43.001+0000 using write concern: w='1', j=false, fsync=false, wtimeout=0
2017-08-08T16:55:43.001+0000 Failed: type coercion failure in document #1 for column 'field_2', could not parse token '' to type int32
2017-08-08T16:55:43.001+0000 imported 0 documents
Run Code Online (Sandbox Code Playgroud)
对于字符串字段,它加载空字符串而不是 null。
我在这里做错了什么?是否可以使用带有 CSV 或 TSV 文件的 mongoimport 将字段加载为 NULL?
无论如何,如果我使用 mongoimport 导入带有 NULL 的 json 文件,它会像实际的 NULL 一样导入它们。
[
{
"field1": "A",
"field2": null,
"field3": "C"
},
{
"field1": 1,
"field2": 5,
"field3": null
}
]
Run Code Online (Sandbox Code Playgroud)
MongoDB 永远不会从 CSV 数据导入空值。
"field": null我猜这是因为考虑到查询将返回所有"field"丢失或为空的文档,这没有太大意义。
该-ignoreBlanks选项将简单地阻止导入为""缺失字段创建空字符串 ( ) 值,否则这些字段将成为默认值。
不过,您可以通过使用以下更新对导入的文档进行后处理来获得所需的内容:
collection.update({'field_2': {$exists: false}}, {$set: {'field_2': null}})
Run Code Online (Sandbox Code Playgroud)