How to create a new collection in MongoDB?

MongoDBDatabaseBig Data Analytics

To create a new collection in MongoDB, you need to use createCollection() method.

Case 1: The easiest syntax to create a new collection in MongoDB is as follows:

db.createCollection(“yourNewCollectionName”);

Case 2: The alternative syntax to create a new collection in MongoDB is as follows:

db.createCollections(“yourNewCollectionName”,options);

The options parameter above can have the following values:

  • capped field which returns boolean type which will either true or false.

  • autoIndexId field which returns boolean type which will either true or false.

  • size field which returns number.

  • max field which returns a number also.

From the above values, the autoIndexed is deprecated from MongoDB version 3.4 and 3.2. We are using MongoDB version 4.0.5. This is how you can also check the current MongoDB version installed on your system:

> db.version();
4.0.5

Case 1: Let us see the query to create a new collection in MongoDB -

> db.createCollection("userInformation");

The following is the output:

{ "ok" : 1 }

To display the created collection, you need to use show command. The query is as follows:

> show collections;

The following is the output:

userInformation

Case 2: Let us see an alternative way to create a new collection in MongoDB. The query is as follows:

> db.createCollection("bookInformation",{capped:true,size:7000000,max:12000});

The following is the output:

{ "ok" : 1 }

Yes we have created a new collection now using the alternative syntax. To display the created collection name, you need to use show command. The query is as follows:

> show collections;

The following is the output displaying the collections we created above:

bookInformation
userInformation
raja
Published on 18-Mar-2019 14:57:33
Advertisements