MongoDB – Create and Insert Collection

This post aims to let you know how to add a record into a collection in MongoDB.

Let’s create a “emp” collection (table) first.

> db.createCollection(“emp”, { capped : true, size : 5242880, max : 5000 } )
Executing the above command will create a collection named “emp” with a maximum size of 5 megabytes and a maximum of 5000 documents. If you do not any limitations, then you can simply use – db.createCollection(“emp”)

Let’s add a record into it.

> db.emp.insert({“empno” : 7839,”ename” : “King”,”job” : “PRESIDENT”,”mgr” : null,”hiredate” : “1981-11-17″,”sal” : 5000,”comm” : null,”deptno” : 10})

Please keep in mind that MongDB is case-sensitive, thus you must take caution while naming your database, collection, and columns. Instead of using NULL, use null.

Let’s see if the record was successfully added.

> db.emp.find( {} )
The above command is as equal as “SELECT * FROM emp” in SQL.
It returns the contents of the specified collection.

{ “_id” : ObjectId(“611b3a67199ab2668eab089c”), “empno” : 7839, “ename” : “King”, “job” : “PRESIDENT”, “mgr” : null, “hiredate” : “1981-11-17”, “sal” : 5000, “comm” : null, “deptno” : 10 }

InsertRecordInCollection
Hope you find this article helpful.

Please subscribe for more interesting updates.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s