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

How to create a new collection in MongoDB?

王林
Release: 2023-09-12 11:25:02
forward
1345 people have browsed it

如何在 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”);
Copy after login

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

db.createCollections(“yourNewCollectionName”,options);
Copy after login

The options parameter above can have the following values:

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

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

  • Returns the size field of the number. The

  • < li>

    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
Copy after login

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

> db.createCollection("userInformation");
Copy after login

The following is the output:

{ "ok" : 1 }
Copy after login
Copy after login

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

> show collections;
Copy after login
Copy after login

Here is the output:

userInformation
Copy after login

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});
Copy after login

Here is the output:

{ "ok" : 1 }
Copy after login
Copy after login

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;
Copy after login
Copy after login

Here is the output showing the collection we created above:

bookInformation
userInformation
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template