Node.js MongoDB Create Collection


पिछले topic में आपने MongoDB connection बनाना सीखा , इस topic में सीखेंगे कि database में collection (table) कैसे बनाये हैं। MongoDB database में collection (table) बनाने के लिए createCollection("collection_name", callback) method का use किया जाता है।

MongoDB Create Collection Example
File : app.js
Copy Fullscreen Close Fullscreen
// import MongoClient from mongodb package
const { MongoClient } = require('mongodb');
const uri = "mongodb+srv://user:pass@cluster0.2n7fz.mongodb.net/node_mongodb?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true ,  connectTimeoutMS: 30000 ,  keepAlive: 1});
// make connection
client.connect(error => {
  if(error){
    console.log("MongoDB Connect Error", error.name, error.message);
  }else{
    // select database
    const database = client.db("node_mongodb");
    const users_collections = database.createCollection("users", (error, result) => {
      if(error){
        console.log("Error : ", error.name, error.message);
      }else{
        console.log("users collection created : ", result);

        // close collection
        client.close();
      }
    });
  }
});
C:\Users\HP\Desktop\workspace\nodejs>node app.js
users collection created :  Collection {
  s: {
    db: Db { s: [Object] },
    options: {
      raw: false,
      promoteLongs: true,
      promoteValues: true,
      promoteBuffers: false,
      ignoreUndefined: false,
      bsonRegExp: false,
      serializeFunctions: false,
      fieldsAsRaw: {},
      enableUtf8Validation: true,
      writeConcern: [WriteConcern],
      readPreference: [ReadPreference]
    },
    namespace: MongoDBNamespace { db: 'node_mongodb', collection: 'users' },
    pkFactory: { createPk: [Function: createPk] },
    readPreference: ReadPreference {
      mode: 'primary',
      tags: undefined,
      hedge: undefined,
      maxStalenessSeconds: undefined,
      minWireVersion: undefined
    },
    bsonOptions: {
      raw: false,
      promoteLongs: true,
      promoteValues: true,
      promoteBuffers: false,
      ignoreUndefined: false,
      bsonRegExp: false,
      serializeFunctions: false,
      fieldsAsRaw: {},
      enableUtf8Validation: true
    },
    readConcern: undefined,
    writeConcern: WriteConcern { w: 'majority' }
  }
}

Example run करें और अगर इसी से Output आता है तो collection create हो चुका है।

Note : MongoDB Database example के लिए हमने यह , पर Online MongoDB Cloud Services use किया है, आप चाहे तो आप database को local पर install करके use में ले सकते हैं।

Node.JS MongDB Show All Colllections

listCollections() method का use करके आप , database में present सभी collections की listing भी कर सकते हैं।

Copy Fullscreen Close Fullscreen
const { MongoClient } = require('mongodb');
const uri = "mongodb+srv://user:pass@cluster0.2n7fz.mongodb.net/node_mongodb?retryWrites=true&w=majority";
const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true ,  connectTimeoutMS: 30000 ,  keepAlive: 1});
// make connection
client.connect(error => {
  if(error){
    console.log("MongoDB Connect Error", error.name, error.message);
  }else{
    // select database
    const database = client.db("node_mongodb");
    database.listCollections().toArray(function(err, collections) {
      if(error){
        console.log("MongoDB Error", error.name, error.message);
      }else{
        for(coll of collections){
          console.log(coll.name)
        }
      }
  });
  }
});
C:\Users\HP\Desktop\workspace\nodejs>node app.js
users

Hey ! I'm Rahul founder of learnhindituts.com. Working in IT industry more than 4.5 years. I love to talk about programming as well as writing technical tutorials and blogs that can help to others .... keep learning :)

Get connected with me - LinkedIn Twitter Instagram Facebook