15

我正在努力使用 mongoimport 从 CSV 文件中导入 Mongodb 的 ObjectId:

我尝试了所有我能想到的组合和转义方法,但无法从 CSV 正确导入 ObjectId。

首先,我尝试将我从 MongoDB 导出的内容准确导入 CSV。我正在使用 MongoDB 2.2.1。

我刚刚创建了两个集合并在另一个文档中引用了一个文档的 _id:

use yourdb
db.createCollection("student")
db.createCollection("class")
db.student.insert({"name":"Peter"})
db.student.find() returns { "_id" : ObjectId("5143af326d44e1ceb372121d"), "name" : "Peter" }
db.class.insert({"student_id": ObjectId("5143af326d44e1ceb372121d"),"name":"II-4"})

然后我在 shell 中使用了 mongoexport 命令:

mongoexport -h localhost:3002 -d yourdb -c classes --csv -f student_id,name > export.txt

生成的 CSV 如下所示:

student_id,name
ObjectID(5143af326d44e1ceb372121d),"II-4"

然后我使用以下方法导入了生成的 CSV:

mongoimport -h localhost:3002 -d yourdb -c class --type csv --file export.txt --headerline

查询类集合现在返回:

db.class.find()
{ "_id" : ObjectId("5143afc66d44e1ceb372121e"), "student_id" :   ObjectId("5143af326d44e1ceb372121d"), "name" : "II-4" }
{ "_id" : ObjectId("5143b44788df173ba096550e"), "student_id" : "ObjectID(5143af326d44e1ceb372121d)", "name" : "II-4" }

如您所见,第二个文档中的 student_id 字段实际上是一个字符串,而不是 MongoDB ObjectId。

我错了,或者 Mongo 无法导入它自己导出的 CSV?

4

2 回答 2

61

对于尝试从 JSON 插入 ObjectIds 的任何有此问题的人 - 通过对现有数据进行一些修改,这很有可能。

代替:

{ "_id" : ObjectId("5143afc66d44e1ceb372121e"),
  "student_id" : ObjectId("5143af326d44e1ceb372121d"),
  "name" : "II-4" }

和:

{ "_id" : {"$oid":"5143afc66d44e1ceb372121e"},
  "student_id" : {"$oid":"5143af326d44e1ceb372121d"},
  "name" : "II-4" }

只需使用正则表达式替换 ObjectId 包装。

于 2015-11-03T19:57:03.497 回答
4

The problem can be reproduced in MongoDB 2.4.1.

The documentation (http://docs.mongodb.org/manual/reference/mongoimport/) states (emphasis by me):

Note Do not use mongoimport and mongoexport for full instance, production backups because they will not reliably capture data type information. Use mongodump and mongorestore as described in “Backup Strategies for MongoDB Systems” for this kind of functionality.

In this discussion https://groups.google.com/forum/?fromgroups=#!topic/mongodb-user/RcnumM5QyxM a similar question was answered as this:

Mongoimport with tsv or csv can only import strings and numbers, and not any of the other types specified in [1]. If you do want to import those types, and if you can produce JSON instead of TSV for your import file, that would be a good way to go; otherwise, you can write a post-processing step which converts the strings to the appropriate MongoDB types (based on some knowledge of what the type of value for a given field should be).

  • Dan

[1] http://www.mongodb.org/display/DOCS/Mongo+Extended+JSON

于 2013-04-02T12:17:15.290 回答