Home >Database >MongoDB >How to create a new collection in MongoDB?

How to create a new collection in MongoDB?

王林
王林forward
2023-09-12 11:25:021341browse

如何在 MongoDB 中创建新集合?

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

Case 1: The simplest syntax for creating a new collection in MongoDB is as follows:

db.createCollection(“yourNewCollectionName”);

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

db.createCollections(“yourNewCollectionName”,options);

The options parameter above can have the following values:

  • Returns a cap field of type Boolean, which is true or false.

    li>
  • autoIndexId field, returns Boolean type, either true or false.

  • Returns the size field of the number. The

  • max field also returns a number.

From the above value, autoIndexed has been deprecated starting from MongoDB versions 3.4 and 3.2. We are using MongoDB version 4.0.5. You can also check the current MongoDB version installed on your system by:

> db.version();
4.0.5

Case 1: Let’s 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 the show command. The query is as follows:

> show collections;

Here is the output:

userInformation

Case 2: Let’s look at another way to create a new collection in MongoDB. The query is as follows:

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

Here is the output:

{ "ok" : 1 }

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

> show collections;

Here is the output showing the collection we created above:

bookInformation
userInformation

The above is the detailed content of How to create a new collection in MongoDB?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete