MongoDB CRUD – Part 2 : Remove item & collection | label:requires_revision

MongoDB CRUD – Part 2 : Remove item & collection | label:requires_revision

This is continue series of MongoDB CRUD – Part 1 : Create collection

MongoDB CRUD – Part 1 : Create collection


Remember! : when you remove fields, technically you remove collection and database, although removing all documents (rows) collection stays empty . There is another method for that (see below for .drop() method) ...


Remove entire field of records (documents) preserving the collection itself :


// ...
async function main() {
    // Use connect method to connect to the server
    await client.connect();
    console.log('Connected successfully to server');

    let targeted_dbName = "mongodb-A-way";
    let targeted_collection = "collection-A-way";
    const db = client.db(targeted_dbName); // console.log("current database: ", db.namespace, " & it's collection: ", db.collection("collection-A-way")["s"]["namespace"].collection);

    await db.collection(targeted_collection).deleteMany({}); // removes entire field of recordS whilst preserving the collection targeted itself
    // await db.collection(targeted_collection).drop(); // drop the targeted db's entire collection (complete remove of the collection targeted)

    return "done.";
}
// ...

Drop the targeted db's entire collection (complete remove of the collection targeted):


async function main() {
    // Use connect method to connect to the server
    await client.connect();
    console.log('Connected successfully to server');

    let targeted_dbName = "mongodb-A-way";
    let targeted_collection = "collection-A-way";
    const db = client.db(targeted_dbName); // console.log("current database: ", db.namespace, " & it's collection: ", db.collection("collection-A-way")["s"]["namespace"].collection);

    // await db.collection(targeted_collection).deleteMany({}); // removes entire field of record**S** whilst preserving the collection targeted itself
    await db.collection(targeted_collection).drop(); // drop the targeted db's entire collection (complete remove of the collection targeted)

    return "done.";
}

Stay tuned , much more is coming up soon !