Skip to content

Instantly share code, notes, and snippets.

@bansalvks
Last active September 19, 2021 04:56
Show Gist options
  • Save bansalvks/c6b5b2bdddc18e0957e26434d165ca1d to your computer and use it in GitHub Desktop.
Save bansalvks/c6b5b2bdddc18e0957e26434d165ca1d to your computer and use it in GitHub Desktop.
mongodb bulk import nested array of objects with new ObjectId
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