Create a MongoDB Collection

Collections are analogous to tables in relational databases, and they store documents (in BSON format) that can be of different structures within a database.

Using the MongoDB Shell

1. Open your terminal and run the MongoDB shell using the mongo command.

2. Choose the database where you want to create a collection using the use command. For example, if you want to create a collection in the "mydatabase" database:

use mydatabase
          

3. Use the createCollection command to create a collection. You can specify the name of the collection and, optionally, its configuration options. For example, to create a collection called "mycollection"

db.createCollection("mycollection")
          

4. You can verify that the collection was created by listing the collections in the current database

show collections
          

Create a collection in Node.js

1. First, you need to import the MongoDB driver into your Node.js application. You can use require to do this

const MongoClient = require('mongodb').MongoClient;
          

2. Use the MongoClient to connect to the MongoDB server. Replace the <connection_string> with your actual MongoDB connection string.

const uri = '<connection_string>';
  MongoClient.connect(uri, (err, client) => {
    if (err) {
      console.error('Error connecting to MongoDB:', err);
      return;
    }
  
    const db = client.db('mydatabase'); // Replace 'mydatabase' with your database name
  
    // Your collection creation code goes here
  
    client.close(); // Close the connection when you're done
  });
            
          

3. To create a collection in MongoDB, you can use the createCollection method on the database object. Replace 'mycollection' with your desired collection name.

db.createCollection('mycollection', (err, res) => {
  if (err) {
    console.error('Error creating collection:', err);
    return;
  }
  console.log('Collection created');
});
          

4. Don't forget to close the connection to the MongoDB server when you're done with your operations

client.close();