'mongoimport choosing field type

When importing data from file (csv in my case) mongoimport automatically choose data type for each field.

Is it possible to choose data type manually for specific field? I encountered situation, when in my file there are phone numbers, which I want and which I should treat as strings, but mongoimport (quite properly) treat those phone numbers as a numbers (NumberLong).



Solution 1:[1]

When importing CSV/TSV to mongodb, the option --columnsHaveTypes can help to define the columnstypes. But the document seems very unclear. I tried several times until finally did succeed. You should add option --columnsHaveTypes and change every column after --fields and remember using "\" before "(" and ")". for example, change:

mongoimport -h foohost -d bardb -c fooc --type tsv --fields col1,col2,col3 --file path/to/file.txt

into

mongoimport -h foohost -d bardb -c fooc --type tsv --fields col1.int32\(\),col2.double\(\),col3.string\(\) --columnsHaveTypes --file path/to/file.txt

Solution 2:[2]

What you can do is import these data using CSV and then run the update statement on the existing data in mongo db to convert it into the format that you want.

Solution 3:[3]

Now version 3.4 onward mongoimport supports specifying the field types explicitly while importing the data. See below link: https://docs.mongodb.com/manual/reference/program/mongoimport/#cmdoption--columnsHaveTypes

Solution 4:[4]

See the Type Fidelity section in the documentation:

mongoimport and mongoexport do not reliably preserve all rich BSON data types because JSON can only represent a subset of the types supported by BSON. As a result, data exported or imported with these tools may lose some measure of fidelity. See MongoDB Extended JSON for more information.

Use mongodump and mongorestore to preserve types.

Solution 5:[5]

When I tried to import CSV into Mongo Atlas, I ran into a similar issue. Here's how I deal with it.

To avoid shell error you can enclose fields in double-quotes.

In the below example, I used two-column "Name, Barcode".You Can use whatever column you need also don't forget to update <connecttionString>,<collectionName>, <CSVpath> with your own values.

for more mongo types refer to mongoimport documentation.

mongoimport --uri <connecttionString> --collection <collectionName> --type csv --file <CSVpath> -f "Name.string(),Barcode.string()" --columnsHaveTypes 

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 Avneesh
Solution 3 Ajinkya
Solution 4 Gergo Erdosi
Solution 5 Asela Priyadarshana