Last active
September 19, 2021 04:56
-
-
Save bansalvks/c6b5b2bdddc18e0957e26434d165ca1d to your computer and use it in GitHub Desktop.
mongodb bulk import nested array of objects with new ObjectId
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const { MongoClient, ObjectID } = require("mongodb"); | |
// Replace the uri string with your MongoDB deployment's connection string. | |
const uri = "MONGODB URI"; | |
const client = new MongoClient(uri); | |
const data = {/** data you want to import */} | |
function addObjectIdToArrayItems(target) { | |
if (Array.isArray(target)) { | |
target.forEach(addObjectIdToArrayItems); | |
} | |
else if (target.toString() === '[object Object]') { | |
target._id = ObjectID() | |
} | |
if(target.children){ | |
addObjectIdToArrayItems(target.children) | |
} | |
} | |
const dbName = 'myDB' | |
const collectionName = 'myCollection' | |
async function run() { | |
try { | |
await client.connect(); | |
const database = client.db(dbName); | |
const collection = database.collection(collectionName); | |
addObjectIdToArrayItems(data) | |
const result = await collection.bulkWrite([ | |
{ | |
insertOne: | |
{ | |
"document": data | |
} | |
} | |
]); | |
console.log(result); | |
} finally { | |
await client.close(); | |
} | |
} | |
run().catch(console.dir); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment