Welcome to plsql4all.blogspot.com SQL, MYSQL, ORACLE, TERADATA, MONGODB, MARIADB, GREENPLUM, DB2, POSTGRESQL.

Saturday, 3 February 2024

How to create Collection in MongoDB

Creating a collection in MongoDB is a straightforward process. MongoDB automatically creates a collection when you insert documents into it. Here's a step-by-step process:


1. Connect to MongoDB:

   - Ensure that your MongoDB server is running.

   - Open a MongoDB shell or connect to your MongoDB server using a MongoDB client.


2. Switch to the Desired Database:

   - If you want to create a collection in a specific database, switch to that database using the `use` command.

     use your_database_name


3. Insert a Document:

   - MongoDB creates a collection when you insert the first document into it. Use the `insertOne` or `insertMany` method to insert a document.

     db.your_collection_name.insertOne({

       key: 'value',

       another_key: 'another_value'

     }) 


4. Verify Collection Creation:

   - Check if the collection has been created using the `show collections` command.

     show collections


   - Alternatively, you can use the `db.getCollectionNames()` method.

     db.getCollectionNames()


5. Create Collection Explicitly (Optional):

   - While MongoDB creates a collection implicitly when you insert a document, you can also create a collection explicitly using the `createCollection` method.

     db.createCollection('your_collection_name')


6. Verify Explicit Collection Creation:

   - Verify the explicit creation of the collection using the same methods as mentioned in step 4.


You've created a collection in MongoDB. Remember that MongoDB is schema-less, so you don't need to define the structure of the collection beforehand. The structure is determined by the documents you insert into it.

No comments:

Post a Comment

Please provide your feedback in the comments section above. Please don't forget to follow.