Mongo Basics
Updated July 2024
Mongo DB is a document-oriented database system that uses the concept of NoSQL. It provides high availability, high performance and automatic scaling. This is an open-source product and was developed by the company – 10gen in October 2007, and also maintains it. MongoDB exists under the General Public License (GPL) as a free database management tool as well as available under Commercial license. Companies of different sizes across all industries are using MongoDB as their database. As of December 2020, the latest available Mongo version is 4.4
Mongo is NOSQL DB
NoSQL as it is used for managing the massive collection of unstructured data and your data is not piled up in a tabular format or relations like that of relational databases. The term NoSQL comes from the word non SQL or non-relational.
Why MongoDB
- It is easy to install the MongoDB.
- It is either schema-free or have relaxed schemas
- It is a document-oriented language and document queries are used which supports dynamic queries.
- Easily scalable.
- It helps in providing fast accessing of data as it uses the internal memory to store the data.
- MongoDB is also used as a file system that can help in easy management of load balancing.
- MongoDB also supports the searching using regex (regular expression) as well as fields.
- Users can run MongoDB as a windows service also.
- It does not require any VM to run on different platforms.
- It also supports sharding of data.
What is database?
In MongoDB, a database can be defined as a physical container for collections of data. Every database has its collection of files residing on the file system. A MongoDB server contains numerous databases.
What are collections?
Collections can be defined as a group of MongoDB documents that exist within a single database. This can be related to a table in a relational database management system. Documents that have collection usually contain different fields. Typically, all the documents residing within a collection are related.
What is a document?
A document can be defined as a collection of key-value pairs which are basic units of data in MongoDB.
{ Name: “Rebecca”, Age: “20”, Groups: [“sports”,”entertainment”] }
Mongo Installations(MAC/Windows)
# Install MongoDB in Windows # Install MongoDB in Linux
Basic CRUD operations
CRUD operations create, read, update, and delete documents.
Create Operations
Create or insert operations add new documents to a collection. If the collection does not currently exist, insert operations will create the collection.MongoDB provides the following methods to insert documents into a collection:
db.collection.insertOne()
db.collection.insertMany()
Please note that these commands are available from Mongo version 3.2 onwards.
Examples
The following example inserts a new document into the inventory collection.
db.inventory.insertOne( {item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" })
The following example inserts three new documents into the inventory collection. If the documents do not specify an _id field, MongoDB adds the _id field with an ObjectId value to each document.
db.inventory.insertMany([ { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" }, { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" }, { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" }, { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" }, { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" } ]);
Mongo Object ID
If the document does not specify an _id field, MongoDB adds the _id field with an ObjectId value to the new document. ObjectIds are small, likely unique, fast to generate, and ordered.The objectId generated by mongoDB is in the following format.
ObjectId(“542c2b97bac0595474108b48”)The _id value provided by the user can be an Integer.
Read Operations
Read operations retrieve documents from a collection; i.e. query a collection for documents. MongoDB provides the following methods to read documents from a collection:
db.inventory.find()
This command returns all the documents from the collectionYou can specify query filters or criteria that identify the documents to return.
Examples
The following command returns the documents with item name “postcard”
db.inventory.find( { item: "postcard" } )
The following command returns the documents with item name “postcard” or “journal”
db.inventory.find( { item: { $in: [ "postcard", "journal" ] } } )
AND condition: The following command returns the documents with status “A” and qty less than 30
db.inventory.find( { status: "A", qty: { $lt: 30 } } )
OR condition: The following command returns the documents with status “A” or qty less than 30
db.inventory.find( { $or: [ { status: "A" }, { qty: { $lt: 30 } } ] } )
The following is a compound query, selects all documents in the collection where the status equals “A” and either qty is less than 30 or item starts with the character p:
db.inventory.find( status: "A", $or: [ { qty: { $lt: 30 } }, { item: /^p/ } ] } )
Update Operations
Update operations modify existing documents in a collection. MongoDB provides the following methods to update documents of a collection:
db.collection.updateOne() db.collection.updateMany() db.collection.replaceOne()
You can specify criteria, or filters, that identify the documents to update. These filters use the same syntax as read operations.
For examples, see Update Documents.
Delete Operations
Delete operations remove documents from a collection. MongoDB provides the following methods to delete documents of a collection:
db.collection.deleteOne() db.collection.deleteMany()
You can specify criteria, or filters, that identify the documents to remove. These filters use the same syntax as read operations.
For examples, see Delete Documents.
Bulk Write
MongoDB provides the ability to perform write operations in bulk. For details, see Bulk Write Operations.
Json schema validator
The $jsonSchema operator matches documents that satisfy the specified JSON Schema.
The $jsonSchema operator expression has the following syntax:
{ $jsonSchema: <JSON Schema object> } { <keyword1>: <value1>, ... }
For example:
{ $jsonSchema: { required: [ "name", "major", "gpa", "address" ], properties: { name: { bsonType: "string", description: "must be a string and is required" }, address: { bsonType: "object", required: [ "zipcode" ], properties: { "street": { bsonType: "string" }, "zipcode": { bsonType: "string" } }}}}}
For a list of keywords supported by MongoDB, see Available Keywords.
Document Validator
You can use $jsonSchema in a document validator to enforce the specified schema on insert and update operations:
db.createCollection( <collection>, { validator: { $jsonSchema: <schema> } } ) db.runCommand( { collMod: <collection>, validator:{ $jsonSchema: <schema> } } )
Examples
Schema Validation
The following db.createCollection() method creates a collection named students and uses the $jsonSchema operator to set schema validation rules:
db.createCollection("students", { validator: { $jsonSchema: { bsonType: "object", required: [ "name", "year", "major", "address" ], properties: { name: { bsonType: "string", description: "must be a string and is required" }, year: { bsonType: "int", minimum: 2017, maximum: 3017, description: "must be an integer in [ 2017, 3017 ] and is required" }, major: { enum: [ "Math", "English", "Computer Science", "History", null ], description: "can only be one of the enum values and is required" }, gpa: { bsonType: [ "double" ], description: "must be a double if the field exists" }, address: { bsonType: "object", required: [ "city" ], properties: { street: { bsonType: "string", description: "must be a string if the field exists" }, city: { bsonType: "string", "description": "must be a string and is required" }}}}}}})
Given the created validator for the collection, the following insert operation will fail because gpa is an integer when the validator requires a double.
db.students.insert({ name: "Alice", year: NumberInt(2019), major: "History", gpa: NumberInt(3), address: { city: "NYC", street: "33rd Street" } }) The operation returns the following error: WriteResult({ "nInserted" : 0, "writeError" : { "code" : 121, "errmsg" : "Document failed validation" } }) After changing the gpa to a double, the insert succeeds: db.students.insert({ name: "Alice", year: NumberInt(2019), major: "History", gpa: 3.0, address: { city: "NYC", street: "33rd Street" } }) The operation returns the following: WriteResult({ "nInserted" : 1 })