The easiest way is just convert the CSV to JSON Array.
To convert a CSV file to JSON format, you can use a CSV parsing library such as csv-parser
in Node.js or the csv
library in Python. Here’s an example in Node.js:
- First, install the
csv-parser
package using npm:
npm install csv-parser
- Next, use the
csv-parser
package to parse the CSV file and convert it to JSON format:
const fs = require('fs');
const csv = require('csv-parser');
const results = [];
fs.createReadStream('path/to/csv/file.csv')
.pipe(csv())
.on('data', (data) => results.push(data))
.on('end', () => {
// Write the JSON output to a file
fs.writeFileSync('path/to/json/file.json', JSON.stringify(results));
});
In this example, the CSV file is read using fs.createReadStream()
and piped to the csv()
function to parse it into an array of objects. The resulting array is then written to a JSON file using fs.writeFileSync()
.
Similarly, in Python you can use the csv
library to convert a CSV file to JSON format:
import csv
import json
csv_file = 'path/to/csv/file.csv'
json_file = 'path/to/json/file.json'
# Read CSV file and convert to list of dictionaries
with open(csv_file, mode='r') as f:
reader = csv.DictReader(f)
data = [row for row in reader]
# Write JSON output to file
with open(json_file, mode='w') as f:
json.dump(data, f)
In this example, the csv.DictReader()
function is used to read the CSV file and convert it into a list of dictionaries. The resulting list is then written to a JSON file using json.dump()
.
==To import a CSV file with an array field in MongoDB, you need to format the array elements in a specific way.==
For example, to import an array field called “items” with two integer values (1 and 2) for each document, you need to format the CSV file like this:
index,UID,items
1,1000,"[1, 2]"
2,1001,"[3, 4]"
Note that the array elements are enclosed in square brackets and separated by a comma and a space. When you import the CSV file using the mongoimport
command, you should specify the --jsonArray
option to indicate that the field is an array type:
mongoimport --db=tabledb --collection=ShopPack --type=csv --columnsHaveTypes --headerline --file=ServerShopPack.csv --ignoreBlanks --jsonArray
This should import the “items” field as an array type in MongoDB.