Creating Collection in MongoDB:
We can create a collection in mongoDB using createCollecion(). This method will take collection name as parameter(collection name is the collection which you want to create).
Syntax:
db.createCollection('<Collection name>',options)
Here, we can also pre-allocate space for new collection. This is optional.
Let's assume, You have to create a collection with name "FirstCollection". You have to run below command.
db.createCollection('FirstCollection')
You can see the created collections using command "show collections".
Inserting Documents:
We can use insert() method to insert documents into a collection. If collection exists then document will be inserted. If not exists, it will create collection first and then it will insert document.
Syntax:
db.<collection Name>.insert()
Below are the sample queries which will insert data into existing collection.
Below are the sample queries which will create collection and then will insert a document.
Note: Before running below queries, collection "StudentData" does not exists.
We can see the inserted documents using find() method. This method will display 20 records by default if we have more than 20 records in the collection.
In MongoDB, data will be stored in JSON format and i am assuming that you are aware of JSON format.
Hope, this gives you basic knowledge to create collection and insert documents into collections.
Thanks.
We can create a collection in mongoDB using createCollecion(). This method will take collection name as parameter(collection name is the collection which you want to create).
Syntax:
db.createCollection('<Collection name>',options)
Here, we can also pre-allocate space for new collection. This is optional.
Let's assume, You have to create a collection with name "FirstCollection". You have to run below command.
db.createCollection('FirstCollection')
You can see the created collections using command "show collections".
Inserting Documents:
We can use insert() method to insert documents into a collection. If collection exists then document will be inserted. If not exists, it will create collection first and then it will insert document.
Syntax:
db.<collection Name>.insert()
Below are the sample queries which will insert data into existing collection.
Below are the sample queries which will create collection and then will insert a document.
Note: Before running below queries, collection "StudentData" does not exists.
We can see the inserted documents using find() method. This method will display 20 records by default if we have more than 20 records in the collection.
In MongoDB, data will be stored in JSON format and i am assuming that you are aware of JSON format.
Hope, this gives you basic knowledge to create collection and insert documents into collections.
Thanks.
Comments
Post a Comment