What are some common use cases for MongoDB and how can it be used in a real-world application?
What is a collection in MongoDB and how to create one?
25416-May-2023
Updated on 18-May-2023
Home / DeveloperSection / Forums / What is a collection in MongoDB and how to create one?
What are some common use cases for MongoDB and how can it be used in a real-world application?
Aryan Kumar
18-May-2023A collection in MongoDB is a group of documents that are related to each other. Collections are similar to tables in a relational database. Each collection has a unique name, and documents in a collection are stored in order by their _id field. The _id field is a unique identifier for each document, and it is automatically generated by MongoDB.
To create a collection in MongoDB, you use the following command:
Code snippet
where:
For example, the following command creates a collection named users:
Code snippet
Once a collection is created, you can insert documents into it using the insert() method. The insert() method takes a list of documents as its argument. The following is an example of how to insert a document into the users collection:
Code snippet
You can also query documents in a collection using the find() method. The find() method takes a query object as its argument. The query object specifies the criteria that documents must match in order to be returned. The following is an example of how to query documents in the users collection:
Code snippet
You can update documents in a collection using the update() method. The update() method takes a query object and an update object as its arguments. The query object specifies the criteria that documents must match in order to be updated. The update object specifies the changes that are to be made to the documents. The following is an example of how to update a document in the users collection:
Code snippet
You can delete documents from a collection using the deleteOne() or deleteMany() method. The deleteOne() method deletes a single document that matches the query object. The deleteMany() method deletes all documents that match the query object. The following is an example of how to delete a document from the users collection:
Code snippet
You can also drop a collection using the drop() method. The drop() method takes the name of the collection to drop as its argument. The following is an example of how to drop the users collection:
Code snippet
Collections are a powerful way to organize data in MongoDB. By understanding how to create, query, update, and delete collections, you can effectively manage data in a MongoDB database.