MongoDB consists of a set of databases. Each database again consists of Collections. Data in MongoDB is stored in collections. The below figure depicts the typical database structure in MongoDB.
Database in MongoDB is nothing but a container for collections. We will learn how to create a new Database, drop a Database and how to use an existing Database in the coming lessons.
db.studytonight.users
to save user informations, then there can be others like db.studytonight.forum.questions
and db.studytonight.forum.answers
to store forum questions and answers respectively.Document in MongoDB is nothing but the set of key-value pairs. These documents will have dynamic schema which means that the documents in the same collection do not need to possess the same set of fields.
Since MongoDB is considered as a schema-less database, each collection can hold different type of objects. Every object in a collection is known as Document, which is represented in a JSON like (JavaScript Object Notation) structure(nothing but a list of key-value pair). Data is stored and queried in BSON, its binary representation of JSON-like data. You can know more about BSON format from this webpage → BSON Specification and BSON Types
Note: In the above figure, the field _id
represents the primary key identifier of the given document. MongoDB also stores the values in the form of arrays of value as well. Infact any type of data can be stored as values, and nothing requires to be pre-defined. In other words, you do not have to predefine the type of data to be stored, you can store anything you want. Remember, MongoDB is schema-less.
Documents are not identified by a simple ID, but by an object identifier type. The default Id is a combination of machine identifier, timestamp and process id to keep it unique, but user can changes it to anything.
{ _id : 112233,
name : "Viraj",
education : [
{
year : 2029,
course : "BTECH",
college : "IIT, Delhi"
},
{
year : 2031,
course : "MS",
college : "Harvard College"
}
]
}
The value of fields in a document can be anything, including other documents, arrays, and arrays of documents, date object, a String etc.
var mydoc = {
_id : ObjectId("5099803df3f4948bd2f98391"),
name : { first: "Alan", last: "Turing" },
birth : new Date('Jun 23, 1912'),
death : new Date('Jun 07, 1954'),
contribs : [ "Turing machine", "Turing test", "Turingery" ],
view : NumberLong(1250000)
}