Articles by "MongoDB"
Showing posts with label MongoDB. Show all posts
Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL

What is MongoDB ObjectId() ?

ObjectIds are small unique ID that generated very fast and ordered. ObjectId values consist of 12 bytes, where the first four bytes are a timestamp that reflect the seconds since the Unix epoch, 5-byte random value, and last 3-byte counter, starting with a random value.

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.

MongoDB ObjectId is generated by MongoDB Drivers and the Server using a default Algorithm. By default typeof MongoDB ObjectId is object.

MongoDB ObjectId 12 bytes can be break up in to following:

Size Description
4 Bytes 4-byte value representing the seconds since the Unix epoch
3 Bytes 3-byte machine identifier
2 Bytes 2-byte process id
3 Bytes 3-byte counter, starting with a random value

Above is a description of MongoDB ObjectId. Most of the time developers requires unique id of the objects to be rendered on web page. In MongoDB ObjectId are the primary key and best for using as unique ID. Therefore here on the progrramers.com we are giving the solution for ‘How to get lowercase hexadecimal mongodb _id string from ObjectId() in MongoDB ?

Below is the example database which we are using the MongoDB tutorial :



> db.cars.find().toArray();
[
{
"_id" : ObjectId("5d53065a520ea88ac000e981"),
"name" : "Ford",
"color" : "blue",
"weight" : "300KG"
},
{
"_id" : ObjectId("5d53066a520ea88ac000e982"),
"name" : "Opel",
"color" : "red"
},
{
"_id" : ObjectId("5d530677520ea88ac000e983"),
"name" : "Mustang",
"color" : "silver"
},
{
"_id" : ObjectId("5d53069f520ea88ac000e984"),
"name" : "porsche",
"color" : "black"
}
]
>


There are many methods available that can be use to extract the lowercase hexadecimal mongodb _id string from MongoDB ObjectId. We will try to approach all possible ways by using MongoDB methods and JavaScript methods as well.

How to get lowercase hexadecimal string from MongoDB ObjectId using ‘valueOf()’ method

Syntax : db.collectionname.findOne()._id.valueOf()

> db.cars.findOne()._id.valueOf();
5d53065a520ea88ac000e981
>


Explanation

In this method first db.collectionname.findOne() will return the JavaScript Object in form of ‘property : value’ pair then by using JavaScript Object. Property method we will get ObjectId() e.g. ‘ObjectId("5d53065a520ea88ac000e981")’. After that valueOf() function extract the lowercase hexadecimal MongoDB _id string e.g. ‘5d53065a520ea88ac000e981’ from MongoDB ObjectId(). The data-type of the result will be ‘string’.

How to get lowercase hexadecimal string from MongoDB ObjectId using ‘str’ method


Syntax : db.collectionname.findOne()._id.str

> db.cars.findOne()._id.str;
5d53065a520ea88ac000e981
>


Explanation

In this method first db.collectionname.findOne() will return the JavaScript Object like above mentioned method e.g. ‘ObjectId("5d53065a520ea88ac000e981")’. After that ‘str’  method extract the lowercase hexadecimal mongodb _id string e.g. ‘5d53065a520ea88ac000e981’ from MongoDB ObjectId(). The data-type of the result will be ‘string’.

How to get value of the ObjectId() in MongoDB using stored functions


There is a special system collection named system.js that can store JavaScript functions for reuse. We can latter call the function using ‘db.eval()’ or ‘db.loadServerScripts()’ methods and get results.

Syntax : db.system.js.save({_id:”functionname”,value:function(parameters){//code here}})

> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.findOne();
... return doc._id.valueOf();
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()")
WARNING: db.eval is deprecated
5d53065a520ea88ac000e981
>

Explanation

Below example first stores the object in ‘doc’ variable in form of ‘property: value’ pair then by using JavaScript Object. Property method we will get ObjectId() e.g. ‘ObjectId("5d53065a520ea88ac000e981")’. After that valueOf() function extract the lowercase hexadecimal MongoDB _id string e.g. ‘5d53065a520ea88ac000e981’ from MongoDB ObjectId(). The data-type of the result will be ‘string’. The whole function expression stored in variable and saved in ‘system.js’ collection.
Note : db.eval is deprecated from MongoDB version 3.2 but finally db.eval is removed from MongDB version 4.2 but db.loadServerScripts() method can be used instead

Above stored function is called using ‘db.eval()’ method, below is another method to call stored function in MongoDB shell.

> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.findOne();
... return doc._id.valueOf();
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.loadServerScripts()
> getObjectID()
WARNING: db.eval is deprecated
5d53065a520ea88ac000e981
>



How to get value of the ObjectId() in MongoDB using plain JavaScript

MongoDB stored functions uses pure JavaScript so it is possible to apply various JavaScript methods to perform a certain task. Now we will see how to get the hexadecimal string in bulk using ‘Array.map()’ function from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... return doc.map(function(i){return i._id.valueOf()});
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


How to get value of the ObjectId() in MongoDB using forEach loop

In this example we will see how to use forEach loop in MongoDB Stored function to extract hexadecimal MngoDB _id string in bulk from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... var myArr = [];
... doc.forEach(element => {
... myArr.push(element._id.valueOf());
... });
... return myArr;
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


How to get value of the ObjectId() in MongoDB using for Loop

In this example we will see how to use for loop in MongoDB Stored function to extract hexadecimal MongoDb _id string in bulk from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... var myArr = [];
... for(var i=0;i<doc.length;i++){
... myArr.push(doc[i]._id.valueOf());
... }
... return myArr;
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


Mongodb compare Objectid to String



> typeof db.cars.findOne().toString();
string
>


How to get value of the ObjectId() in MongoDB using JavaScript substring

In this example we will see how to use JavaScript substring method in MongoDB Stored function to extract hexadecimal MongoDB _id string from ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.findOne();
... return doc._id.toString().substring(10, 34);
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
5d53065a520ea88ac000e981
>


Same method can be used to extract hexadecimal MongoDB _id string in bulk from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... return doc.map(function(i){
... return i._id.toString().substring(10, 34)
});
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


How to get value of the ObjectId() in MongoDB using JavaScript slice

In this example we will see how to use JavaScript slice method in MongoDB Stored function to extract hexadecimal MongoDb _id string from ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.findOne();
... return doc._id.toString().slice(10, 34);
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
5d53065a520ea88ac000e981
>


Same method can be used to extract hexadecimal string in bulk from JavaScript Arrary of ObjectId().


> db.system.js.save({
... _id:"getObjectID",
... value:function(){
... var doc = db.cars.find().toArray();
... return doc.map(function(i){
... return i._id.toString().slice(10, 34)
});
... }
... });
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
> db.eval("return getObjectID()");
WARNING: db.eval is deprecated
[
"5d53065a520ea88ac000e981",
"5d53066a520ea88ac000e982",
"5d530677520ea88ac000e983",
"5d53069f520ea88ac000e984"
]
>


How to get typeof the ObjectId() in MongoDB using JavaScript

Getting the typeof ObjectId()


> typeof db.cars.findOne()._id;
object
>


How to get the typeof function variable stored in system.js



> typeof db.eval("return getObjectID()");
WARNING: db.eval is deprecated
object
>

How to get the typeof output value



> typeof db.eval("return getObjectID()")[0];
WARNING: db.eval is deprecated
string
>


Related Topics


Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL
Hello world! We have seen How to do CRUD operation in MongoDB earlier now it’s time to know what are data type which helps us create more efficient database using MongoDB. MongoDB supports more than 15 data types but more important is that what kind of data type is basically used to store the documents.

MongoDB uses bin­ary-en­coded seri­al­iz­a­tion of JSON-like doc­u­ments called BSON to store documents and make remote procedure calls. Like JSON, BSON sup­ports the em­bed­ding of doc­u­ments and ar­rays with­in oth­er doc­u­ments and ar­rays. BSON also con­tains ex­ten­sions that al­low rep­res­ent­a­tion of data types that are not part of the JSON specifications. Being more specific BSON is a binary format in which zero or more ordered key/value pairs are stored as a single entity. We call this entity a document.

Data type is an important part of Database. When you store the data in database with proper data type it reflects faster performance, therefore data type is important. For e.g. a number can be stored as an integer or string both but if we require numbers later for mathematical calculation then it is good to store the numerical value as integer to get faster mathematical calculations.

In MongoDB each BSON type has both integer and string identifiers as listed in the following table:

Type Number Alias Notes
Double 1 “double”
String 2 “string”
Object 3 “object”
Array 4 “array”
Binary data 5 “binData”
Undefined 6 “undefined” Deprecated.
ObjectId 7 “objectId”
Boolean 8 “bool”
Date 9 “date”
Null 10 “null”
Regular Expression 11 “regex”
DBPointer 12 “dbPointer” Deprecated.
JavaScript 13 “javascript”
Symbol 14 “symbol” Deprecated.
JavaScript (with scope) 15 “javascriptWithScope”
32-bit integer 16 “int”
Timestamp 17 “timestamp”
64-bit integer 18 “long”
Decimal128 19 “decimal” New in version 3.4.
Min key -1 “minKey”
Max key 127 “maxKey”

Some of the most important data types are explained below:

String

String data type is the most commonly used datatype to store the data. String in MongoDB must be UTF-8 valid. MongoDB $regex queries support UTF-8 in the regex string.

NumberDecimal

The decimal BSON data type uses the IEEE 754 decimal128 floating-point numbering format which supports 34 decimal digits (i.e. significant digits) and an exponent range of −6143 to +6144. Decimal 128 datatype is introduced in 3.4 version of MongoDB.

NumberLong (Integer)

The mongo shell treats all numbers as floating-point values by default. The mongo shell provides the NumberLong() wrapper to handle 64-bit integers.

NumberInt (Integer)

The mongo shell treats all numbers as floating-point values by default. The mongo shell provides the NumberInt() constructor to explicitly specify 32-bit integers.

Date

BSON Date is a 64-bit integer that represents the number of milliseconds since the Unix epoch (Jan 1, 1970). This results in a representable date range of about 290 million years into the past and future.


Timestamp

BSON has a special timestamp type for internal MongoDB use and is not associated with the regular Date type. Timestamp values are a 64 bit value where the first 32 bits are a time_t value (seconds since the Unix epoch) and the second 32 bits are an incrementing ordinal for operations within a given second.

Within single mongod instance timestamp values are always unique.

Array

Arrays are the data type that can store single or multiple arrays or values within a single key.

Object

Objects are the data type that used for embedded documents

Object ID

ObjectIds are small unique ID that generated very fast and ordered. ObjectId values consist of 12 bytes, where the first four bytes are a timestamp that reflect the seconds since the Unix epoch, 5-byte random value, and last 3-byte counter, starting with a random value.

In MongoDB, each document stored in a collection requires a unique _id field that acts as a primary key. If an inserted document omits the _id field, the MongoDB driver automatically generates an ObjectId for the _id field.

MongoDB Tutorial : How to get lowercase hexadecimal string from MongoDB ObjectId() – Mongodb Objectid Operations.

Boolean

This data type is store Boolean values i.e. True or False.

Min/Max Keys

This type is used to compare a value against the lowest and highest BSON elements. The min and max keys indicate that the system should avoid normal query planning. Instead they construct an index scan where the index bounds are explicitly specified by the values given in min and max.

Null

This data type is used to store null data.

Binary data

This data type is used to store binary form of data.

Regular Expression

This data type is used to store regular expression.

Data Modeling in MongoDB

Unlike SQL databases, where you must determine and declare a table’s schema before inserting data, MongoDB’s collections, by default, does not require its documents to have the same schema. Data in MongoDB has a flexible schema documents in the same collection. They offer to create different fields, structure and data types in and common fields in same collection. This flexibility gives you data-modeling choices to match your application and its performance requirements.


Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL
Hello Programmers! In previous chapters we were introduced with MongoDB. Now we know that MongoDB is NoSQL database program that provides a mechanism for storage and retrieval of data in documents of tree structured collections and also we learnt ‘how to create/remove database and collections in MongoDB shell'.



Before we go ahead in this MongoDB Tutorial, let's take a tour on CRUD operation in any database.

What is CRUD Operations in database?

Any database program can perform only four possible operations as mentioned below :
  1. Create or Insert data/ documents in database
  2. Read or Select or Find data/documents from database
  3. Update data/document in database
  4. Delete data/document from database
Create, Read, Update and Delete operations are whole together called CRUD Operations in database program.
In this chapter of MongoDB Tutorial series we will see how to Insert, find, update and delete the documents in MongoDB shell.
So let’s go ahead and see how it is done. In previous post we have created database named ‘cricket’ and inside that database we have created a collection named ‘teamindia’. Now we go to perform CRUD Operations on that database through MongoDB Shell.

MongoDB : Create or insert Operation

Create or insert operations add new document to a collection. If the collection does not currently exist, insert operations will create the collection and add the document. Check the example for your reference

>db.teamindia.insertOne({
name:"Virat Kohali",
role:["Batsman", "Captain"],
batting:"Right-Hand Middle-Order",
bowling:"Right-Arm-Medium",
});
>□


Above is the example of insert single document to a collection. In MongoDB, insert operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.
In other words, atomicity means "indivisibility" and "irreducibility”. MongoDB write operations are atomic, only at the level of a single document. If you're modifying multiple subdocuments inside a document the operation is still atomic, but if you're modifying multiple documents, the operation is not atomic.

>db.teamindia.insert({
name:"M.S.Dhoni",
role:["Wicketkeeper", "Batsman"],
batting:"Right-Hand Lower-Middle-Order",
bowling:"Right-Arm-Medium",
});
>□


MongoDB shell provides following Methods to insert document in a collection :
  • db.collectionname.insert() – insert one or more document at same time
  • db.collectionname.inserOne() – insert one document at a time (Introduced in MongoDB 3.2)
  • db.collectionname.insertMany() – insert multiple document at a time (Introduced in MongoDB 3.2)

Mathod: db.collectionname.insert();

Using this method you can insert one or multiple document at a single write. It takes single data as a JavaScript object. MongoDB provides clients the ability to perform write operations in bulk. In this method, it takes array of JavaScript objects to insert multiple data at single write. Must check the below example carefully :
Example of db.collectionname.insert()

Mathod: db.collectionname.insertOne();

Using this method you can insert single document in a collections. It takes single data as a JavaScript object.
Example

Mathod: db.collectionname.insertMany();

Using this method you can insert one or multiple documents at a single write. Like db.collectionname.insert() method this (db.collectionname.insertMany()) method also takes array of JavaScript objects to insert multiple data at single write.


>db.teamindia.insertMany([
{
name:"Sikhar Dhawan",
role:["Batsman"],
batting:"Left-Hand Opener",
},
{
name:"Rohit Sharma",
role:["Batsman", "Vice Captain"],
batting:"Right-Hand Opener",
},
{
name:"Kedar Jadav",
role:["Allrounder","Batsman", "Bowler"],
batting:"Right-Hand Middle-Order",
bowling: "Right-Arm-Slinger-Off-Break"
},
{
name:"Rabindra Jadeja",
role:["Allrounder","Batsman", "Bowler"],
batting:"Left-Hand Lower-Middle-Order",
bowling: "Left-Arm-Off-Break"
},
{
name:"Jasprit Bumrah",
role:["Batsman", "Bowler"],
batting:"Right-Hand Talender",
bowling: "Right-Arm-Fast-Medium"
},
]);
>□


Check the above example carefully, Data in MongoDB has a flexible schema documents in the same collection. They do not need to have the same set of fields or structure, and common fields in a collection’s documents may hold different types of data.You can see in the above example.

With MongoDB, you may embed related data in a single structure or document. These schema are generally known as “denormalized” models, and take advantage of MongoDB’s rich documents. Embedded data models allow applications to store related pieces of information in the same database record.

Difference between db.collectionname.insert() and db.collectionname.insertMany() : progrramers explanation

The major difference between these two methods is the output response value after performing insert and insertmany operations. When inserting multiple document using insert method, you will get the response as BulkWriteResult() in JSON format (see in the below image) while inserting multiple document using insertMany you will get the acknowledge status as true/false and an array of ObjectId of inserted documents (see in the below image).

MongoDB Tutorial - difference between insert and insertMany
MongoDB Tutorial - difference between insert and insertMany


Note : The output response value is most important thing while you are working as professional. Professional programmers use the methods as per their requirement of output (return) values. Progrramers also suggest using the insert method as per requirement of response value.

MongoDB : Read or find Operation

Read or find operation retrieves the documents from collections.
MongoDB shell provides following Methods to query document in collections :
  • db.collectionname.find(); - find entire document(s) from a collection at a time
  • db.collectionname.findOne(); - find the single document from a collection (Introduced in MongoDB 3.2)

Mathod : db.collectionname.find();

Using this method you can retrieve the document in a collection and it returns a cursor of the selected documents. You can specify query criteria, projection and other filters to this method like motioned in below example :

>db.teamindia.find()
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f13"),
"name" : "Sikhar Dhawan",
"role" : [
"Batsman"
],
"batting" : "Left-Hand Opener"
}
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f14"),
"name" : "Rohit Sharma",
"role" : [
"Batsman",
"Vice Captain"
],
"batting" : "Right-Hand Opener"
}

>□

While dealing with multiple output results, we can arrange

Method : db.collectionname.findOne();

Using this method you can retrieves the document as per query criteria and it returns a single document. If the criteria matches with multiple records it returns first document in collection according to the natural order which reflects the order of documents on the disk.

>db.teamindia.findOne()
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f13"),
"name" : "Sikhar Dhawan",
"role" : [
"Batsman"
],
"batting" : "Left-Hand Opener"
}

>□


MongoDB : Update Operation

Using update operation you can modify existing document in a collection. MongoDB provides the following methods to update documents of a collection:
  • db.collection.update (); - Update document(s) in a collection
  • db.collection.updateOne(); - Update single document in a collection (Introduced in MongoDB 3.2)
  • db.collection.updateMany(); - Update multiple document in a collection (Introduced in MongoDB 3.2)
  • db.collection.replaceOne(); - Replace the entire content of a document except for the _id field (Introduced in MongoDB 3.2)

Method : db.collectionname.updateOne();

Using this method you can update single document in a collection. It also takes multiple parameters as filter criteria. When filter criteria matches with multiple document then it updates the first matching document in the collection.

>db.teamindia.findOne({batting : "Left-Hand Opener"})
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f13"),
"name" : "Sikhar Dhawan",
"role" : [
"Batsman"
],
"batting" : "Left-Hand Opener"
}
> db.teamindia.updateOne({"name" : "Sikhar Dhawan"},{$set:
{"batting" : "Right-Hand Opener"}})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
> db.teamindia.findOne({batting : "Left-Hand Opener"})
null
>□

Method : db.collectionname.updateMany();

Using this method you can update multiple documents in a collection. It also takes multiple parameters as filter criteria. When filter criteria matches with multiple document then it updates the all matching document in the collection.

> db.teamindia.find({"batting" : "Right-Hand Opener"}).pretty()
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f13"),
"name" : "Sikhar Dhawan",
"role" : [
"Batsman"
],
"batting" : "Right-Hand Opener"
}
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f14"),
"name" : "Rohit Sharma",
"role" : [
"Batsman",
"Vice Captain"
],
"batting" : "Right-Hand Opener"
}
> db.teamindia.updateMany({"batting" : "Right-Hand Opener"},{$set :
{"batting" : "Left-Hand Opener"}})
{ "acknowledged" : true, "matchedCount" : 2, "modifiedCount" : 2 }
>□


Method : db.collectionname.replaceOne();

With this method your replace single document in a collection. It also takes multiple parameters as filter criteria like db.collectionname.updateOne(). When filter criteria matches with multiple document then it replaces the first matching document in the collection.

> db.teamindia.find({"name" : "Rohit Sharma"}).pretty()
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f14"),
"name" : "Rohit Sharma",
"role" : [
"Batsman",
"Vice Captain"
],
"batting" : "Left-Hand Opener"
}
> db.teamindia.replaceOne({"name" : "Rohit Sharma"},{"name" : "Rohit Kohali",
"batting"
: "Right-Hand Opener","bowling":"Right-Arm Off Breack"})
{ "acknowledged" : true, "matchedCount" : 1, "modifiedCount" : 1 }
>□



Note : All above update methods take special Boolean parameter. If upsert : true then new document will added to collections if no match found with filter criteria or if match found then the existing document will be update.


MongoDB: Delete Operation

Delete operations remove documents from a collection. MongoDB provides the following methods to delete documents of a collection.
  • collection.remove(); - Removes single and multiple documents from a collection
  • collection.deleteOne(); - Removes single document form a collection (Introduced in MongoDB 3.2)
  • collection.deleteMany(); - Removes multiple or entire documents form a collection (Introduced in MongoDB 3.2)
In MongoDB, delete operations target a single collection. All write operations in MongoDB are atomic on the level of a single document.

You can specify criteria, or filters, that identify the documents to remove. These filters use the same syntax as read operations.

Method: db.collectionname.remove();

In MongoDB, the db.collection.remove() method removes documents from a collection. You can remove all documents from a collection, remove all documents that match a condition, or limit the operation to remove just a single document.

>db.teamindia.remove({"name" : "Rohit Sharma"});
WriteResult({ "nRemoved" : 1 })
>□


Removing Single Document from a collection

To remove a single document, call the remove() method with the justOne parameter set to true or 1.

Method: db.collectionname.deleteOne();

This method deletes the first document that matches the filter. You can use the unique index such as _id field for exact match.

>db.teamindia.deleteOne({"name" : "Kedar Jadav"});
WriteResult({ "nRemoved" : 1 })
>□

Method: db.collectionname.deleteMany();

This method deletes the entire documents that match the filter.

>db.teamindia.deleteMany({"batting" : "Right-Hand Talender"})
{ "acknowledged" : true, "deletedCount" : 3 }
>□

MongoDB Tutorial : How to get lowercase hexadecimal string from MongoDB ObjectId() – Mongodb Objectid Operations.
Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL
Hello Programmers! In previous chapter we have seen How to create/remove database using MongoDB shell, in this chapter will see How to create/remove collection using MongoDB Shell? But before we go ahead we should know that what the MongoDB collections are?

MongoDB Tutorials - How to create-remove collections using MongoDB shell
MongoDB Tutorial : How to create/remove collection using MongoDB Shell? - Progrramers

What is MongoDB Collections?

A group to MongoDB documents can be referred as a collection. A collection is the equivalent of an RDBMS table. A collection exists within a single database. Collections do not enforce a schema. Documents within a collection can have different fields. Data in MongoDB can have different schema documents in the same collection.

> db.teamindia.find().toArray()
[
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f13"),
"name" : "Sikhar Dhawan",
"role" : [
"Batsman"
],
"batting" : "Left-Hand Opener"
},
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f14"),
"name" : "Rohit Sharma",
"role" : [
"Batsman",
"Vice Captain"
],
"batting" : "Right-Hand Opener"
},
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f15"),
"name" : "Kedar Jadav",
"role" : [
"Allrounder",
"Batsman",
"Bowler"
],
"batting" : "Right-Hand Middle-Order",
"bowling" : "Right-Arm-Slinger-Off-Break"
},
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f16"),
"name" : "Rabindra Jadeja",
"role" : [
"Allrounder",
"Batsman",
"Bowler"
],
"batting" : "Left-Hand Lower-Middle-Order",
"bowling" : "Left-Arm-Off-Break"
},
{
"_id" : ObjectId("5d5e2e6cd1c0b7eafe211f17"),
"name" : "Jasprit Bumrah",
"role" : [
"Batsman",
"Bowler"
],
"batting" : "Right-Hand Talender",
"bowling" : "Right-Arm-Fast-Medium"
}
]
>

db.createCollection() Method

Below is the basic syntax of Create Collection Command:

db.createCollection(<name>, <options>);
db.createCollection() method take two parameters:
  • Name : Name of the collection to be created
  • Option : Specify options about memory size and indexing (Optional)
In the command, name is name of collection to be created. Options is a document and is used to specify configuration of collection.

> use cricket
switched to db cricket
> db.createCollection("teamindia");
{ "ok" : 1 }
> □

Above example explains how you can create a basic collection without use of options.

Parameter Type Description
Name String Name of the collection to be created
Options Document (Optional) Specify options about memory size and indexing

Options parameter is optional, so you need to specify only the name of the collection like above example. Following is the list of options you can use :

Field Type Description
capped Boolean (Optional) If true, enables a capped collection. Capped collection is a fixed size collection that automatically overwrites its oldest entries when it reaches its maximum size. If you specify true, you need to specify size parameter also.
autoIndexId Boolean (Optional) If true, automatically create index on _id field.s Default value is false.
size number (Optional) Specifies a maximum size in bytes for a capped collection. If capped is true, then you need to specify this field also.
max number (Optional) Specifies the maximum number of documents allowed in the capped collection.

Now let’s try to create a collection using few parameters like mentioned in above table.

> db.createCollection("players", { capped : true, autoIndexId : true, size :
... 10485760, max : 20000 } )
{
"note" : "the autoIndexId option is deprecated and will be removed in a
future release",
"ok" : 1
}
>□

Example Explanation

Above is an example of creating a collection using ‘capped’, ‘autoIndexId’, ‘size’ and ‘max’ parameters. ‘capped’ parameter enables capped collections that has a fixed size which is specified in ‘size’ parameter - 10485760 bytes (10MB). After the reaching at its size limit, it will overwrite the previous entries. This collection can store maximum 20000 documents that specified in max parameter. autoIndexId parameter creates on _id field by default.

Note: you have to be careful while using autoIndex parameter because the autoIndexId option is deprecated and will be removed in a future release

Collections can be created automatically

MongoDB creates a new collection while you are inserting first document using a collection name and after that you can also insert documents in that collection. So you do not need to create the collections, collections can be created automatically.

> db.language.insert({

... name:"JavaScript",
... type:"Client Side",
... tutorial: "Progrramer JavaScript Tutorials"
... });
WriteResult({ "nInserted" : 1 })
> show collections
language

players
sample
system.indexes
teamindia
> db.language.find().toArray()

[
{
"_id" : ObjectId("5d62d624ed9a7864410433ef"),
"name" : "JavaScript",
"type" : "Client Side",
"tutorial" : "Progrramer JavaScript Tutorials"
}
]
>□


In above example collection named ‘language’ is created when first document is inserted.

Show Collections

In MongoDB, to view the list of collections inside a database show collection command is use.
Below example shows first switch to database using use command and then get list of collections by using show collections command.

> show collections
players
sample
system.indexes
teamindia
>

Remove Collections

To remove or delete the collection in MongoDB drop() command is used. Below is the basic syntax of drop() collection.

db.collectionname.drop();

You can check the collection in collections list and drop the collection. In below example a collection named language is dropping.

> show collections
language
players
sample
system.indexes
teamindia


> db.language.drop()
true


> show collections
players
sample
system.indexes
teamindia
>
Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL
Hello Programmers! In previous chapter we were introduced with MongoDB. Now we know that MongoDB is NoSQL database program that provides a mechanism for storage and retrieval of data in documents of tree structured collections.

MongoDB Tutorials - how to create-remove database using MongoDB shell
MongoDB Tutorials : How to create/remove database using MongoDB shell? - progrramers


In this MongoDB Tutorial we will see how to create a Database in MongoDB.

use Command

In MongoDB ‘use command’ is used to create database. ‘use Command’ is also used to switch to another existing database. The command creates a new database if database is not existing otherwise it returns existing database.

Below is the basic syntax of use command :

use <database_name>

> use cricket
switched to db cricket
>


Above is example of use command that shows how to create a new to database.

db Command

db command shows the name of database that currently in use. By default ‘test’ database is selected but you can switch to other existing database by using ‘use command’.


> db
cricket
>




show dbs Command

Show dbs command shows the list of database existed in MongoDB.


> show dbs
admin 0.078GB
cars 0.078GB
company 0.078GB
cricket 0.078GB
demo 0.078GB
local 0.078GB
myapp 0.078GB
mydb 0.078GB
school 0.078GB
test 0.078GB
>


Note: When you create new database using use command and then check the database list using show dbs, you will not find the new created database in this list until you do not create at least a collection in that database. By default ‘test’ database is selected if not creating new database then collection will be created and stored in ‘test’ database.

Now we will see how to drop a database using MongoDB command.

dropDatabase() Method

In MongoDB dropDatabase() method is used to drop database.

Below is the basic syntax of Drob Database Command:

dropDatabase()
Switch to existing database using ‘use’ Command and write down the command dropDatabase() and hit Enter button and your existing database is deleted.


> use demo
switched to db demo
> db.dropDatabase()
{ "dropped" : "demo", "ok" : 1 }
> show dbs
aams 0.078GB
admin 0.078GB
cars 0.078GB
company 0.078GB
cricket 0.078GB
local 0.078GB
myapp 0.078GB
mydb 0.078GB
school 0.078GB
test 0.078GB
>


dropDatabase() command deletes the selected database therefore you do not required to write any other filter criteria. If you haven’t select any database then it delete ‘test’ database by default.

Next chapter in this tutorial series will elaborate How to create/remove collection using MongoDB Shell?
Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL

What is Mongo Shell?

Mongo Shell is a practice field for beginners and can be used to perform advance administrative operation as well. Database and collections can be created, accessed, modified and deleted using MongoDB shell. Mongo Shell is a component of MongoDB Distributions. It is an interactive JavaScript interface to MongoDB.

What is Mongo Shell?

What is Mongo Shell?



Mongo shell can be use to perform the CRUD operations. Once you have installed and have started MongoDB, connect the mongo shell to your running MongoDB instance.
MongoDB supports AD hoc queries like field, range query, and regular expression searches. Queries can return specific fields of documents and also include user-defined JavaScript functions. Queries can also be configured to return a random sample of results of a given size.


db.cars.find({color:"red"});

//Result : { "_id" : ObjectId("5d53066a520ea88ac000e982"), "name" : "Opel", "color" : "red" }

How to start MongoDB Shell?

To start MongoDB you have to install MongoDB first on your PC. You can easily setup MongoDB on your pc by taking reference of the below “How to Link”.

MongoDb Tutorial : How to Install MongoDB?

If you have Window OS 32-bit then you need to go MongoDB installed program file location (by default – “C:\Program Files\MongoDB\Server\3.2\bin\”) and double-click on mongod.exe to start the MongoDB instance and after that find another file named mongo.exe in same directory, double-click on that and MongoDB shell will be started.

How to Start MongoDB Shell in Window7 32-Bit - progrramers.com
How to Start MongoDB Shell in Window7 32-Bit - progrramers.com


Else if you have Window OS 64-bit you need to go MongoDB installed program file location (by default – “C:\Program Files\MongoDB\Server\4.0\bin\”) and double-click on mongo.exe, MongoDB shell will be start along with the MongoDB instance.


Progrramers Recommends : Best Practice

Set the Path for MongoDB instance and MongoDB Shell in Windows Environment Variables.

Store a JavaScript Function on the Server - MongoDB Stored Procedure Equivalent (MongoDB Procedure Operations)

Store Procedure is the best way to extract faster performance from database programs because it minimizes the gap between data and database program. A stored procedure is a set of database statements that has been created and stored in the database. A stored procedure accepts input parameters from server side script and performs the task so that a single procedure can be used over the network by several clients using different input data.

There is nothing called store procedure in MongoDB but MongoDB provides a highly efficient mechanism to perform the task like store procedure. MongoDB documents can store the JavaScript functions as data which can accept the parameters and execute the function accordingly.
In MongoDB JavaScript functions can be saved in system.js document and execute later when required. For reference check below example:


db.system.js.save(
    {
        _id:"getSum",value:function(a, b){
            return a + b
        }
    }
);

db.eval("return getSum(2, 6)");
// Result : 8

CRUD operations in MongoDB Shell

Like other database program MongoDB shell can be used to perform CRUD operations. CRUD operations refer to the basic functions like Create, Read (Find), Update and Delete.

MongoDB Shell: Create or insert operation

Create or insert operation adds new document inside a collection. If there is no collection found with specified name then first it creates the collection with specified name and then inserts a new document inside a collection.
MongoDB shell provides following Methods to insert document in collection.
  • collectionname.insert() – insert one or more document at same time
  • collectionname.inserOne() – insert one document at a time
Note : In MongoDB insert operation can target single collection at a time. MongoDB stores the data in the document in the form of field and value. Values are case sensitive during query operations for example “Apple” is different from “apple” when finding the document with search criteria like {fruit : “apple”}.

MongoDB Shell: Read or Find Operation 

Read or Find operation retrieves the data from a collection. Find operation can use regex to find the specific pattern of data and execute the result accordingly. MongoDB shell provides following methods to find the document from a collections.
  • collectioname.find() – find whole document available in a collection
  • collectioname.findOne() – find top most document available in result in a collection
  • collection.find().forEach(printjson) – find whole document available in a collection and output the result in JSON oriented format
  • collection.find().pretty() – find whole document available in a collection and output the result in JSON oriented format
Note : MongoDB stores the data in the document in the form of field and value. Values are case sensitive during query operations for example “Apple” is different from “apple” when finding the document with search criteria like db.collection.find({fruit : “Apple”}) and db.collection.find({fruit : “apple”}) both return the different value.



MongoDB Shell: Update Operation 

Update operation can modifies the exiting document in a collection. You can specify criteria, or filters, that identify the documents to update. These filters use the same syntax as read operations. Update operation can also use regex to find the specific pattern of data and execute the result accordingly. Like mentioned above in read operation values are case sensitive in specified criteria.
  • collection.updateOne() – Update one record as per specified criteria
  • collection.updateMany() – Update many record as per specified criteria
  • collection.replaceOne() – Replace one record as per specified criteria

MongoDB Shell: Delete Operations

Delete operations remove documents from a collection. You can specify criteria, or filters, that identify the documents to update. These filters use the same syntax as read operations and update operations. Delete operation can also use regex to find the specific pattern of data and execute the operation accordingly. Like mentioned above in read and update operation values are case sensitive in specified criteria.


Related Topics

What Is MongoDB? : Introduction, MongoDB Architecture, NoSQL Concept And Comparison With SQL Database
MongoDb Tutorial : How to Install MongoDB?

Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL

MongoDb Tutorial : How to Install MongoDB?

MongoDb Tutorial : How to Install MongoDB?


Hello World! Welcome to MongoDB Tutorial Series. In this post we will learn  How to Install MongoDB to our personal computer. In order to install MongoDB to windows PC we have to download the installer package of MongoDB from MongoDB official site. The link is given below, you simply click it, go to the MongoDB site and download the installer file.
Remember : The installer package available on MongoDB site is only for 64-bit OS architecture.

How to check the OS Architecture ?

In order to check your Windows OS architecture you can go through these options. Try any one of these and know your system OS architecture.

1. Check the Properties of My Computer like show in below image:


MongoDB Tutorial - How to get OS Architecture in Windows 7 using MyComputer Properties.jpg
MongoDB Tutorial - How to get OS Architecture in Windows 7 using MyComputer Properties.jpg

or


2. Go to Command and Type ‘wmic os get osarchitecture’ and press enter you will get the OS architecture as shown in below figure :

MongoDB Tutorial - How to get OS Architecture in Windows 7 using DOS Commands.jpg
MongoDB Tutorial - How to get OS Architecture in Windows 7 using DOS Commands.jpg

or
3. At last open ‘Run’ and type ‘dxdiag’ and press enter, Direct-X diagnostic tool will be open where you can find the OS architecture:

MongoDB Tutorial - How to get OS Architecture in Windows 7 using Direct-X Tool.jpg
MongoDB Tutorial - How to get OS Architecture in Windows 7 using Direct-X Tool.jpg

Download Mongodb for Windows OS 64-Bit

The following tutorial uses the MongoDB installation wizard to install MongoDB Community Edition 4.0 on Windows 64-Bit OS.
Download MongoDB Community Edition 4.0.12 for Windows 64-Bit OS
Download MongoDB Community Edition with Multiple Choice

Download Mongodb for Windows 7 32-Bit

If you want to install MongoDB for Windows 7 32-bit then click the below link and download the package.
Download MongoDB Other Version Binaries
Note : To work better it is preferred to install Window 7 Service Pack 1 for 32-bit OS architecture. To download the same click the below link:
Window 7 Service Pack All in One
Above link might not work after 14th January 2020. Therefore keep back-up also.

Remember : 32-bit version of MongoDB only supports database smaller then 2GB and strongly preferred for study and testing purpose only.

MongoDB Installation Procedure

After downloading the installer (.msi file) package you have to run this package, so click the double click the installer file and follow the installation wizard. You will be asked to choose the set type : Complete (recommended for most users)  or Custom. If you choose the Custom installation option, you may have to specify the location of installation file.
After that you will be asked to choose the type of service configuration like shown in below image. If you want to install the MongoDB binaries only then uncheck the check box or if you want to run install MongoDB as service then you need to check the checkbox.

MongoDB install Binaries only or Install as service
MongoDB install Binaries only or Install as service


MongoDB install as service : This configuration allows you to configure MongoDB as service. Every time you start window MongoDB initialized automatically.
  • Run the service as Network Service user (Default) :This is a Windows user account that is built-in to Windows.
  • Run the service as a local or domain user
    • For an existing local user account, specify a period (i.e. ) for the Account Domain and specify the Account Name and the Account Password for the user.
    • For an existing domain user, specify the Account Domain, the Account Name and the Account Password for that user.
MongoDB install binaries only : With this configuration you have to start MongoDB manually every time when starting the windows.

Service Name : Specify the service name. Default name is MongoDB. If you already have a service with the specified name, you must choose another name.

Data Directory : Specify the data directory, which corresponds to the --dbpath. If the directory does not exist, the installer will create the directory and sets the directory access to the service user.

Log Directory : Specify the Log directory, which corresponds to the --logpath. If the directory does not exist, the installer will create the directory and sets the directory access to the service user.


How to set up path for Window 7 32-Bit ?

In Window 32-Bit installation it is little bit difficult to set the path to run MongoDB instance. So you have be care full while setting the path in commands. First you have to run Command as Administrator.

How to start Command as Administrator?

To start command as Administrator click on ‘start menu’ and type ‘cmd’ in search program. You will find the command black icon in start menu list. Right click on command icon and click on ‘Run as Administrator’.  You will come to command prompt : c:\windows\system32. For you reference image is attached.

How to start Command as Administrator?
How to start Command as Administrator?


In MongoDB 32-bit, your default installation file location will be ‘C:\Program Files\MongoDB\Server\3.2\bin’ unless you customize it. Therefore go inside the bin directory of the installation file location in command like shown in below image.

How to setup path of MongoDB in Window 7 32-Bit
How to setup path of MongoDB in Window 7 32-Bit


Now go to path C:\Program Files\MongoDB\Server\3.2 and create two folders. First folder name should be ‘data’ and second should be ‘log’. Also inside the data directory create another folder names ‘db’. After create these folders go back to command prompt and type(show in below images) : mongod.exe --storageEngine=mmapv1 --dbpath C:\Program Files\MongoDB\Server\3.2\data\db --logpath C:\Program Files\MongoDB\Server\3.2\log\mongo.log --logappend --rest --install



How to setup dbpath of MongoDB in Window 7 32-Bit
How to setup dbpath of MongoDB in Window 7 32-Bit


This post will be in continuing. Please check letter for updates. If you any query please type in the comments. We feel glad to help you. Thank you and have nice day...!


Related Topics


What Is MongoDB? : Introduction, MongoDB Architecture, NoSQL Concept And Comparison With SQL Database

 


Progrramers is optimized for Web Development Tutorials, Framework7, MeanStack, MongoDB, ExpressJS, AngularJS, NodeJS, HTML, CSS, JavaScript, PHP, SQL
Hello World! This is my brand new post and you are cordially welcome. Here we are about to be introduced with ‘MongoDB’.

MongoDB Image : What is MongoDB ? Progrramers Blog

What is MongoDB?

MongoDB is a general purpose, cross-platform, document-oriented distributed database program with the high flexibility and easy scalability. Unlike SQL MongoDB stores data in JSON like documents with flexibility. The term ‘flexibility’ is used here which means you are not bound to a fixed data field structure or predefined database schema. Field can be differing from document to document. Mongo DB works on the concept of collections and documents.

In SQL database, data stored in relational tabular form where MongoDB is NoSQL database program that provides a mechanism for storage and retrieval of data in documents of tree structured collections.

Before being too much descriptive let’s check out a brief example. Let’s assume we have a data table named persons in SLQ like below image.

SQL Database Example


In above figure there are four fields in table named person - First name, last name, email and age. If people want to feed the entire field then its fine which is shown in case of John Miller but take a close look on Steve Smith row, he doesn’t want to feed the email ID. In this case the email field is left empty in Steve Smith’s row. Next case of Edmond Woods who also wants to feed his address but there is no field of address is predefined therefore he cannot feed his address.  To do so database handler must define an address field in person’s table schema but the problem is that if John Miller and Steve Smith don’t want to feed their address then the address field of their rows will leave empty.

The synopses of the above example that you must predefined the schema of every expected data-field either user fill them or not while working with SQL. This can create lots of null data in your table which occupies small amount of space in your database, even though it is very small but it does.
Now let’s move on and check an example of MongoDB.

MongoDB Database Example


 Above image is showing the persons collection where the data is stored in the form of JSON-Objects.

You can notice the there is no predefined schema of person’s collection. John Miller is updated all the four fields but take a close look once again on Steve Smith he didn’t update the email ID and there is no field is predefined for email. Edmond Woods who updated the address but there is no field named address is defined for John Miller and Steve Smith.

This feature of MongoDB (NoSQL) database make it extreme flexible and worthy. The distributed systems design allows you to intelligently put data where you want it and supports a wide variety of data and queries. It avoids creating useless null data into database.
MongoDB grow horizontally through native sharding. A database shard is a horizontal partition of data in a database. Each individual partition is referred to as a shard or database shard. Each shard is held on a separate database server instance, to spread load. This feature allows scaling the database easily.

It is essential to compare SQL and MongoDB to understand the basic architecture and functionality of the MongoDB (NoSQL) database. Now we have a brief understanding of MongoDB database. To work with MongoDB you must have command over the JavaScript language, especially JavaScript Object and JavaScript Object Notation (JSON).


Related Topics

MongoDb Tutorial : How to Install MongoDB?