6

I have a mongo document with a structure like: { "foo": { "bar1": "val1", "bar2": "val2"} } I'd like to import my data from a csv using mongoimport --type csv --headerline [...]

I am not sure how to format the field name in the csv to address the nested structure. For instance:

test.csv:

foo.bar1
example

returns { "_id" : ObjectId("4e9d9d25c5d8708e1f51cdbc"), "foo.bar1" : "example" } instead of the desired output:

{ "_id" : ObjectId("4e9d9d25c5d8708e1f51cdbc"), "foo: {"bar1" : "example"} }

The field name seems to be interpreted as a string regardless of its value. Things like foo[bar1] and foo: {bar1} are also used verbatim.

Jason Winget
  • 313
  • 3
  • 11
  • This may not currently be possible. From [this thread](http://groups.google.com/group/mongodb-user/browse_thread/thread/4d516486b4ac01c2/de29edd7e2fe94be?lnk=gst&q=mongoimport+nested#de29edd7e2fe94be): No way to do nesting with csv. Kind of a weird api. Suggestions/patches welcome – Jason Winget Oct 18 '11 at 17:12

2 Answers2

9

This isn't supported in the current (v2.0) version of mongoimport, but it should be coming soon. You can check out the JIRA ticket here, scheduled for v2.1:

Until then, if you can translate your CSV data to JSON then you could use mongoimport --type json to import the nested data.

EDIT: This feature is released now, and available from 2.8.0-rc0

Andrew Nessin
  • 1,206
  • 2
  • 15
  • 22
Chris Fulstow
  • 41,170
  • 10
  • 86
  • 110
1

You can add a column in CSV like parent_key.array_index.nested_key

CSV data example

CSV data example

JSON object image in mongo db after import

JSON object image in mongo db after import

Muhammad Tarique
  • 1,407
  • 1
  • 13
  • 17