Error import a date (DD-MM-YYY) from CSV file to mongoDB with mongo import

848 views
Skip to first unread message

hernan...@gmail.com

unread,
Mar 21, 2018, 3:05:38 AM3/21/18
to mongodb-user
I have a csv file with a date field in format DD-MM-YYYY.

I try: 
mongoimport --db dbName --collection collectionName --type csv --columnsHaveTypes --fields "purchase_date.date()" --file /home/user/Documents/filename.csv 

the error:
Failed: type coercion failure in document #0 for column 'Fecha_Inicial', could not parse token 'Fecha_Inicial' to type date

Thanks for someone to help me.

Kevin Adistambha

unread,
Mar 26, 2018, 3:12:23 AM3/26/18
to mongodb-user

Hi

You need to specify the date format in the date() specification.

For example, if I have a CSV of:

John,2000-01-02
Jack,1998-05-03

I can import it with:

mongoimport --type csv --columnsHaveTypes --fields "name.string(),birthday.date(2006-01-02)" --file test.csv

Note the date(2006-01-02) field. The date specification is using Go’s date specification method, which is a bit unorthodox. See Go date format spec for more information. This quote from the linked page explains how it works:

// The reference time used in the layouts is the specific time:
//    Mon Jan 2 15:04:05 MST 2006
// which is Unix time 1136239445. Since MST is GMT-0700,
// the reference time can be thought of as
//    01/02 03:04:05PM '06 -0700
// To define your own format, write down what the reference time would look
// like formatted your way;

The resulting import is:

> db.test.find()
{
  "_id": ObjectId("5ab89c0fbfed9d9279dcff08"),
  "name": "Jack",
  "birthday": ISODate("1998-05-03T00:00:00Z")
}
{
  "_id": ObjectId("5ab89c0fbfed9d9279dcff09"),
  "name": "John",
  "birthday": ISODate("2000-01-02T00:00:00Z")
}

Best regards
Kevin

Reply all
Reply to author
Forward
0 new messages