MongoDB CRUD – Part 1 : Create collection | label:requires_revision

MongoDB CRUD – Part 1 : Create collection | label:requires_revision

This is intro chapter of MongoDB CRUD series

Intro into MongoDB nutshell of working process


Everyone knows MongoDB is object-based (non-relational) type of database . The interesting part of MongoDB is that a database is created within the moment the collection is created unless it's just append process of extra collection to some already existing database (ignore the later case for now) . Such behaviour is self explanatory : everything is an object in MongoDB . One or more objects (row[s] in SQL) are technically a collection (table in SQL), a one or more collection(s) (table[s]) composes the database[s] (a.k.a. scheme[s]) . Of course we can exploit use statement (it's case sensitive!) on MongoDB Shell (mongosh) which is pretty much like in MySQL environment , although use clause behaviour is slightly different as it only switches to named database e.g. when use command was run , the output of such would be switched to db mongodb on the MongoDB Shell . Nevertheless being instantiated with use it's still not a physical database, rather than an idiomatical allocation of such . We must insert some record(s) i.e. documents to initiate our non-existing database filled up with collection(s) within . There are several approaches to achieve such goal :..

Initial code for A & B-way :

import { MongoClient } from 'mongodb';

const connectionURL = 'mongodb://127.0.0.1:27017'; // overwise SRV for Atlas
let label = "A-way"; const database = `mongodb-${label}`;

A-way

The following shows how to create collection using db.createCollection() method :

NOTICE! : this method is useful only if collection does not exist, otherwise if collection already exists , do consume the scenario presented below (B-way) :


// If used on already existing database will throw a MongoServerError: Collection already exists.

// Connection URL
const client = new MongoClient(connectionURL);
async function main() {
    // Use connect method to connect to the server
    await client.connect();
    console.log('Connected successfully to server');
    const db = await client.db(database);
    const collection = await db.createCollection(`collection-${label /* unless specified otherwise */}`);
    await collection.insertOne({"A" : label /* unless specified otherwise */}); 

    return 'done.';
}
main()
  .then(console.log)
  .catch(console.error)
  .finally(() => client.close()); // close to prevent memory leak (recommended!)

.createCollection() reference


B-way

The following shows how to create collection using db.collection("nonExistingDatabaseCollection").insertOne(); method :

IMPORTANT! : Rather than .createCollection() method as present in the example above , .collection() does not throw any error by keeping the namespace reference of the collection through the targeted database that ensures repetition availability by inserting records (documents) multiple times . Let's examine the following example (some parts are removed for the matters of simplified context)


// ...
// let label = "B-way";
// ...
async function main() {
    // Use connect method to connect to the server
    await client.connect();
    console.log('Connected successfully to server');
    const db = await client.db(database);
    await db.collection("nonExistingDatabaseCollection").insertOne({"B" : label /* unless specified otherwise */});

    return 'done.';
}
// ...

.collection() reference


Ending word : we should put await functions outside inside try catch statements that I ignored this time so the code would be easier picked up by beginner's eye .


Other chapters of MongoDB CRUD :

  1. MongoDB CRUD – Part 2 : Remove item & collection
  2. Much more is coming up soon , stay on frequency !