Web Programming TutorialsLearn About Different Data Types and Methods in MongoDB

Learn About Different Data Types and Methods in MongoDB

In this chapter, we are going to explore data types, insert and save method, find method, projection method and the pretty method in the MongoDB. We are going to learn so much more as we progress in this MongoDB tutorial series.

Data Types
The following table is the summary of the available data types in MongoDB.

S No.

Data Types

Description

1.

String

String data type must be UTF-8 valid in MongoDB and it is most commonly used to store data.

2.

Integer

It is used to store integer (numerical) values. Depending on the DB server it could be 32-bit or 64-bit.

3.

Boolean

It is used to store a boolean value. It can have only two values i.e. true or false.

4.

Double

It is used to store the floating point values in MongoDB.

5.

Min/ Max keys

It is used to compare a value against the lowest and highest BSON elements.

6.

Arrays

Arrays as a data type can be used to store arrays or list or multiple values into one key.

7.

Timestamp

It is the data type that stores the timestamp while storing or updating a document into the MongoDB.

8.

Object

It is used for the embedded documents operations.

9.

Null

It is used to store the Null Values into MongoDB.

10.

Symbol

It is used in a similar way as we use String to store String data. The only difference is that the Symbol data type is reserved for languages that use a specific symbol type.

11.

Date

It is used to store dates in the MongoDB. Date could be the current date or time in UNIX time format. Also, we can create our own date time by creating object of Date and passing day, month, year into it.

12.

Object ID

It is used to store the document’s ID in the MongoDB.

13.

Binary data

It is used to store the binary data in the MongoDB.

14.

Code

It is used to store the JavaScript code into the document

15.

Regular expression

It is used to store regular expressions in the MongoDB.

Insert and Save method to store a document in MongoDB
In this section, we are going to discuss how to insert a document in the MongoDB Collection. The following are the syntaxes.
We can insert data into the MongoDB collection by using either MongoDB’s ‘insert ()’ or ‘save ()’ method.

Syntax
The following is the basic syntax for insert () command in MongoDB.

> db.COLLECTION_NAME.insert(document)

Example
The following is an example on using the insert () statement.

> db.test.insert ( { title: 'Insert Statement',description: 'MongoDB Tutorial', company: 'Eduonix Learning Inc.'})
WriteResult({ "nInserted" : 1 })
> db.test.find()
{ "_id" : ObjectId("5813eed6e6893b80c9ae5bba"), "abc" : 100 }
{ "_id" : ObjectId("5814c9b689c20c164089fbe7"), "title" : "Insert Statement", "description" : "MongoDB Tutorial", "company" : "Eduonix Learning Inc." }
>

Explanation of the code

  • Here, we are using the default ‘test’ collection name of MongoDB.
  • We are issuing an insert command without specifying the _id parameter. In such a case, MongoDB will generate a unique ObjectId for this document with three fields i.e. title, description and company.
  • _id parameter is a 12 bytes hexadecimal number unique assigned to every document in a MongoDB collection. This is how these 12 bytes are divided as follows:
_id: ObjectId(4 bytes are timestamp, 3 bytes are machine id, 2 bytes are process id, and 3 bytes are incrementer)

Note: We can insert multiple documents in a single query by using an array of documents inside an ‘insert ()’ command.

> db.test.save ( [ { title: 'Array1', description: 'Mongo1', company: 'Eduonoix', tags: ['abc','def','ijk'] }, {title: 'Array2', description: 'Mongo2', company: 'Edunoix', tags: ['123', '456', '789'] } ] )
BulkWriteResult({
        "writeErrors" : [ ],
        "writeConcernErrors" : [ ],
        "nInserted" : 2,
        "nUpserted" : 0,
        "nMatched" : 0,
        "nModified" : 0,
        "nRemoved" : 0,
        "upserted" : [ ]
})
>

single-query
Syntax
The following is the basic syntax for save () command in MongoDB.

> db.COLLECTION_NAME.save(document)

Example
The following is an example of using the save () statement.

> db.test.save ( { title: 'save Statement',description: 'MongoDB Tutorial2', company: 'Eduonix Learning Inc.'})
WriteResult({ "nInserted" : 1 })
> db.test.save ( {"_id" : ObjectId("5813eed6e6893b80c9ae5bba"), title: 'save Statement with id', description: 'MongoDB Tutorial save with object id', company: 'Eduonix Learning Inc.'})
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.test.find()
{ "_id" : ObjectId("5813eed6e6893b80c9ae5bba"), "title" : "save Statement with id", "description" : "MongoDB Tutorial save with object id", "company" : "Eduonix Learning Inc." }
{ "_id" : ObjectId("5814c9b689c20c164089fbe7"), "title" : "Insert Statement", "description" : "MongoDB Tutorial", "company" : "Eduonix Learning Inc." }
{ "_id" : ObjectId("5814cbb389c20c164089fbe8"), "title" : "save Statement", "description" : "MongoDB Tutorial2", "company" : "Eduonix Learning Inc." }
>

Note: The ‘save ()’ method works in a similar way to that of an ‘insert ()’ method when do not specify _id in the document. If we specify an id then the ‘save ()’ method will replace the whole data of the document containing _id (i.e. modifying the existing record) as given in ‘save ()’ method.
document-containing

Find method to retrieve documents in MongoDB
We use ‘find ()’ method to query data from the MongoDB collection. The following is the syntax and a demonstration example.

Syntax
The following is the basic syntax for ‘find ()’ command in MongoDB.

> db.COLLECTION_NAME.find()

Example
The following is an example on the use of the find () statement.

> db.test.find()
{ "_id" : ObjectId("5813eed6e6893b80c9ae5bba"), "title" : "save Statement with id", "description" : "MongoDB Tutorial save with object id", "company" : "Eduonix Learning Inc." }
{ "_id" : ObjectId("5814c9b689c20c164089fbe7"), "title" : "Insert Statement", "description" : "MongoDB Tutorial", "company" : "Eduonix Learning Inc." }
{ "_id" : ObjectId("5814cbb389c20c164089fbe8"), "title" : "save Statement", "description" : "MongoDB Tutorial2", "company" : "Eduonix Learning Inc." }
{ "_id" : ObjectId("5814d1c389c20c164089fbea"), "title" : "Array1", "description" : "Mongo1", "company" : "Eduonoix", "tags" : [ "abc", "def", "ijk" ] }
{ "_id" : ObjectId("5814d1c389c20c164089fbeb"), "title" : "Array2", "description" : "Mongo2", "company" : "Edunoix", "tags" : [ "123", "456", "789" ] }
>

Note: The ‘find ()’ method, when used, will display all the documents from the MongoDB collection in a non-structured way. In addition to the ‘find ()’ method, there is ‘findOne ()’ method that returns only one document.

Pretty Method to display formatted documents in MongoDB
We use ‘pretty ()’ method to query data from the MongoDB collection in a formatted way unlike ‘find ()’ command. The following is the syntax and a demonstration example.

Syntax
The following is the basic syntax for ‘pretty ()’ command in MongoDB.

> db.COLLECTION_NAME.find().pretty ()

Example
The following is an example on the use of the pretty () statement.

> db.test.find().pretty()
{
        "_id" : ObjectId("5813eed6e6893b80c9ae5bba"),
        "title" : "save Statement with id",
        "description" : "MongoDB Tutorial save with object id",
        "company" : "Eduonix Learning Inc."
}
{
        "_id" : ObjectId("5814c9b689c20c164089fbe7"),
        "title" : "Insert Statement",
        "description" : "MongoDB Tutorial",
        "company" : "Eduonix Learning Inc."
}
{
        "_id" : ObjectId("5814cbb389c20c164089fbe8"),
        "title" : "save Statement",
        "description" : "MongoDB Tutorial2",
        "company" : "Eduonix Learning Inc."
}
{
        "_id" : ObjectId("5814d1c389c20c164089fbea"),
        "title" : "Array1",
        "description" : "Mongo1",
        "company" : "Eduonix",
        "tags" : [
                "abc",
                "def",
                "ijk"
        ]
}
{
        "_id" : ObjectId("5814d1c389c20c164089fbeb"),
        "title" : "Array2",
        "description" : "Mongo2",
        "company" : "Edunoix",
        "tags" : [
                "123",
                "456",
                "789"
        ]
}
>

pretty-method

Projection concept in MongoDB
In MongoDB, the projection concept helps retrieve only the required fields instead of all the fields of the documents present in a collection by using the ‘find ()’ command. Therefore, if a MongoDB collection has 6 fields and we want to retrieve only 2 fields, then with the help of projection, we can achieve this.

In MongoDB, when you execute the ‘find ()’ command on a particular collection then it displays all the fields present in all the documents associated with that collection. Now, in order to limit the required fields, we need to set a list of fields with the appropriate values. We set value as 1 or 0. 1 to show a field and value as 0 to hide a field.

Syntax
The following is the basic syntax for projection in MongoDB.

> db.COLLECTION_NAME.find({},{KEY:1})

Example
The following is an example on the use of the projection in MongoDB. We are using the default collection ‘test’ for this example.

> db.test.find ( {}, {“title”:1})
{ “_id” : ObjectId(“5813eed6e6893b80c9ae5bba”), “title” : “save Statement with id” }
{ “_id” : ObjectId(“5814c9b689c20c164089fbe7”), “title” : “Insert Statement” }
{ “_id” : ObjectId(“5814cbb389c20c164089fbe8”), “title” : “save Statement” }
{ “_id” : ObjectId(“5814d1c389c20c164089fbea”), “title” : “Array1” }
{ “_id” : ObjectId(“5814d1c389c20c164089fbeb”), “title” : “Array2” }
> db.test.find ( {}, {“title”:1, _id:0})
{ “title” : “save Statement with id” }
{ “title” : “Insert Statement” }
{ “title” : “save Statement” }
{ “title” : “Array1” }
{ “title” : “Array2” }
>

Explanation of code

  • In the first projection command, we have issued to display only the title field of the documents. However, we can see that the _id filed is also displayed. This is because, the _id field is always displayed by default when we execute the ‘find ()’ method.
  • In the second projection command, we have suppressed the _id field by issuing the key as ‘_id:0’. Hence, we can see that only the title field is displayed on the screen as shown below.
    projection-command

Conclusion
In this chapter, we have learnt about the various data types present in MongoDB and the practical use of insert, save, find, findOne, and pretty methods with the help of numerous examples. Also, later in the chapter we have covered the projection concept of MongoDB where we can limit the display of document fields present in a MongoDB’s collection.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -