MongoDB – AppDividend https://appdividend.com Latest Code Tutorials Thu, 01 Nov 2018 21:59:15 +0000 en-US hourly 1 https://wordpress.org/?v=5.2 https://appdividend.com/wp-content/uploads/2017/08/cropped-ApDivi-32x32.png MongoDB – AppDividend https://appdividend.com 32 32 MongoDB CRUD Operations Tutorial With Example https://appdividend.com/2018/10/29/mongodb-crud-operations-tutorial-with-example/ https://appdividend.com/2018/10/29/mongodb-crud-operations-tutorial-with-example/#comments Mon, 29 Oct 2018 16:08:54 +0000 http://localhost/wordpress/?p=2012 CRUD Example in MongoDB

MongoDB CRUD Operations Tutorial With Example is today’s leading topic. MongoDB stores data in the form of BSON – Binary encoded JSON documents which supports a substantial, rich collection of types. Namely, Fields in BSON documents may hold arrays of values or embedded documents as a requirement. The record in MongoDB is a document which is described […]

The post MongoDB CRUD Operations Tutorial With Example appeared first on AppDividend.

]]>
CRUD Example in MongoDB

MongoDB CRUD Operations Tutorial With Example is today’s leading topic. MongoDB stores data in the form of BSON – Binary encoded JSON documents which supports a substantial, rich collection of types. Namely, Fields in BSON documents may hold arrays of values or embedded documents as a requirement. The record in MongoDB is a document which is described below and a data structure formed of field and value pairs.

Want to learn to code, gain a new skill and get a new job. Check out this amazing program

MongoDB CRUD Operations Tutorial

CRUD operations refer to the basic Create(Insert), Read, Update and Delete operations.

#1: Start Mongo Server and Mongo Shell

Now, first start the mongo server using the following command.

mongod

Also, start the mongo shell using the following command.

mongo

#2: Create a database and collection.

Now, switch to an existing database or create a new Mongodb database using the following command.

use crud

So, we switched to that database.

Now, create a collection using the following command. Let us call the collection operate.

db.createCollection("operate")

So, the collection is created. MongoDB stores the documents in the collections. Collections are somewhat same as tables in relational databases. If the collection does not exist then MongoDB creates the collection for you when you first store data for that collection.

#3: Create Operations in MongoDB

Create or insert operations add new documents to the collection. If the collection does not currently exist then insert operations will create the collection.

The command db.collection.insert() will perform the insert operation into the collection of the document.

db.operate.insert({
	enrollno: "110470116021",
	name: "Krunal Lathiya",
        college: "VVP Engineering College",
	course: {
		courseName: "BE IT",
		duration: "4 Years"
	},
	address: {
		city: "Rajkot",
		state: "Gujarat",
		country: "India"
	}
})

It will insert a document in MongoDB.

You can check it by fetching that document using this query.

db.operate.find().pretty()

 

MongoDB CRUD Operations Tutorial With Example

# Insert Multiple Documents in MongoDB

MongoDB provides us the following methods to insert the documents into a collection.

  • db.collection.insertMany()

The syntax is following.

db.collection.insertMany(
   [ <document 1> , <document 2>, ... ],
   {
      writeConcern: <document>,
      ordered: <boolean>
   }
)

It returns the following document containing:

Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Checkout this amazing program
  • A boolean acknowledged as valid if the operation ran with write concern or false if write concern was disabled.
  • An array of _id for each successfully inserted documents.

We can insertMany documents like the following code.

db.operate.insertMany([{
	enrollno: "110470116021",
	name: "Krunal Lathiya",
  college: "VVP Engineering College",
	course: {
		courseName: "BE IT",
		duration: "4 Years"
	},
	address: {
		city: "Rajkot",
		state: "Gujarat",
		country: "India"
	}
},{
  enrollno: "110470116022",
	name: "Rushikesh Vekariya",
  college: "VVP Engineering College",
	course: {
		courseName: "BE IT",
		duration: "4 Years"
	},
	address: {
		city: "Rajkot",
		state: "Gujarat",
		country: "India"
	}
}])

 

MongoDB CRUD Operations

#4: MongoDB Read Operations

Read operations retrieves the documents from the collection; i.e., queries the collection for the documents. MongoDB provides us the following methods to read the documents from the collection.

db.collection.find()

Let us retrieve all the documents using the following query.

 

MongoDB Read Operations

You can specify the query filters or criteria that identify the documents to return.

db.operate.find().limit(2)

Also, we can get the pretty results.

db
 .operate
 .find()
 .limit(2)
 .pretty()

#5: MongoDB Update Operations

Update operations modify existing documents in the collection. MongoDB provides us the following methods to update the documents of the collection.

  • db.collection.updateOne()
  • db.collection.updateMany()
  • db.collection.replaceOne()

You can write the update query in MongoDB like below.

db.operate.updateOne(
  { name: "Rushikesh Vekariya" },
  {
    $set: {college: "Marwadi"}
  }
)

 

MongoDB Update Operations

In MongoDB, the update operations target the single collection. All the write operations in MongoDB are atomic on the level of the single document.

We can also run an update on many documents like following.

db.operate.updateMany(
  { name: "Krunal Lathiya" },
  {
    $set: {city: "Jetpur"}
  }
)

In the operate collection, we have two documents whose name is Krunal Lathiya so that it will update both the documents using updateMany.

The db.collection.replaceOne() replaces a single document within the collection based on the filter.

The replaceOne() method has the following syntax.

db.collection.replaceOne(
   <filter>,
   <replacement>,
   {
     upsert: <boolean>,
     writeConcern: <document>,
     collation: <document>
   }
)

#6: MongoDB Delete Operations

The delete operations remove the documents from the collection. MongoDB provides the following methods to delete the documents of the collection.

  • db.collection.deleteOne()
  • db.collection.deleteMany()
db.operate.deleteOne(
  { name : "Krunal Lathiya" }
)

So, it will remove the document which has name Krunal Lathiya.

Same syntax but deleteMany function, which deletes all the documents with the provided name.

Finally, MongoDB CRUD Operations Tutorial With Example is over.

The post MongoDB CRUD Operations Tutorial With Example appeared first on AppDividend.

]]>
https://appdividend.com/2018/10/29/mongodb-crud-operations-tutorial-with-example/feed/ 2
MongoDB MapReduce Example Tutorial https://appdividend.com/2018/10/26/mongodb-mapreduce-example-tutorial/ https://appdividend.com/2018/10/26/mongodb-mapreduce-example-tutorial/#respond Fri, 26 Oct 2018 16:24:52 +0000 http://localhost/wordpress/?p=1999 MapReduce Command in MongoDB

MongoDB MapReduce Example Tutorial is today’s leading topic. MapReduce is the data processing mechanism for condensing large volumes of data into useful aggregated results. MongoDB uses MapReduce command for map and reduce operations. MapReduce is used for processing large data sets. In straightforward terms, the MapReduce command takes two primary inputs, the mapper function, and the reducer function. Want to learn to […]

The post MongoDB MapReduce Example Tutorial appeared first on AppDividend.

]]>
MapReduce Command in MongoDB

MongoDB MapReduce Example Tutorial is today’s leading topic. MapReduce is the data processing mechanism for condensing large volumes of data into useful aggregated results. MongoDB uses MapReduce command for map and reduce operations. MapReduce is used for processing large data sets. In straightforward terms, the MapReduce command takes two primary inputs, the mapper function, and the reducer function.

Want to learn to code, gain a new skill and get a new job. Check out this amazing program

The Mapper will start by reading the collection of data and building the Map with the required fields that we need to process and group them into one array. And then this key-value pair is fed into the Reducer, which will transform the values. MapReduce is a framework which allows parallelizing the processing of large and extensive data sets across many physical or virtual servers. The typical Map/Reduce program consists of two phases:

  1. map phase: filter / transform / convert data
  2. reduce phase: perform aggregations over the data

MongoDB MapReduce Example Tutorial

To some extent, the map and reduce phases were inspired by map and reduce, the high-order functions widely used and well known in the functional programming world in JavaScript. As the name MapReduce implies, the map job is always performed before the reduce job.

Example

Let us say; we have the following data.

[
    {
        name: Krunal,
        age: 26
    },
    {
        name: Krunal,
        age: 25
    },
    {
        name: Ankit,
        age: 24
    },
    {
        name: Ankit,
        age: 25
    },
    {
        name: Rushabh,
        age: 26
    },
    {
        name: Rushabh,
        age: 27
    }
]
Earn a Tech Degree and get the skills like Frontend Development or Javascript Development that can help you to launch a career. Check out this amazing program

Now, we need to apply the MapReduce function and see what we get as an output.

And we want to count the age for all the customers with the same name. We will run this data through the Mapper function and then the Reducer to achieve the result.

When we ask the Mapper function to process the above data without any conditions, it will generate the following result.

Key
Krunal [26,25]
Ankit [24, 25]
Rushabh [26,27]

So, we have applied the map method and generate a key-value pair, where the key is name and value is an array of grouped age values based on their keys.

Now, we can apply the reduce method to add their ages and return the grouped reduced values. So we have used these operations to process the values and get the desired output. So, in the reducer function, we get the first row from the above table, and now we need to process it. We will iterate through all the values and add them. It will be the sum for the first row and next, the reducer will receive the second, and it will do the same thing, till all the rows are completed.

Name Total
Krunal 51
Ankit 49
Rushabh 53

So now you can understand why the Mapper function is called a Mapper (because it will create a map of data in the form of a key-value pair) & why the Reducer is called the Reducer (because it will reduce the data that the mapper has generated to a more simplified form).

MapReduce on MongoDB

First, create a mongodb database and collection using the following command.

use mapreduce
db.createCollection("blogs")

Now, insert some documents.

db.blogs.insert({
  "title" : "AppDividend",
  "published" : "2017-03-27",
  "authors": [
      { "firstName" : "Krunal",  "lastName" : "Lathiya" }
  ],
  "categories" : [ "Angular", "React", "Vue" ]
})

db.blogs.insert({
  "title" : "Demonuts",
  "published" : "2016-12-10",
  "authors": [
      { "firstName" : "Krunal",  "lastName" : "Lathiya" }
  ],
  "categories" : [ "Android", "PHP" ]
})

db.blogs.insert({
  "title" : "Scotch.io",
  "published" : "2011-12-10",
  "authors": [
      { "firstName" : "Chris",  "lastName" : "Sevilleja" }
  ],
  "categories" : [ "React", "Laravel", "Vue", "Angular", "MongoDB", "PHP", "Android" ]
})

The map-reduce function first queries the collection and then maps the result documents to emit the key-value pairs.

The syntax is following.

db.collection.mapReduce(
   function() {emit(key,value);},  //map function
   function(key,values) {return reduceFunction}, {
      out: collection,
      query: document,
      sort: document,
      limit: number
   }
)
  1. The map is a javascript function that maps a value with a key and emits a key-value pair.
  2. The reduce is a javascript function that reduces or groups all the documents having the same key.
  3. The out specifies the location of the map-reduce query result.
  4. The query specifies the optional selection criteria for selecting documents.
  5. The sort specifies the optional sort criteria.
  6. The limit specifies the optional maximum number of documents to be returned.

Now, we will find how many blogs one author has with its first name and last name.

For that, the command is the following.

db.runCommand( {
    mapReduce: "blogs",
    map: function(){
        for (let index = 0; index < this.authors.length; ++index) {
            let author = this.authors[ index ];
            emit( author.firstName + " " + author.lastName, 1 );
        }
    },
    reduce: function(author, counters){
        count = 0;

        for (let index = 0; index < counters.length; ++index) {
            count += counters[index];
        }

        return count;
    },
    out: { inline: 1 }
} )

MongoDB MapReduce Example Tutorial

So, this is how we can process the large data with MapReduce Function in MongoDB.

Finally, MongoDB MapReduce Example Tutorial is over. Thanks for taking.

The post MongoDB MapReduce Example Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/10/26/mongodb-mapreduce-example-tutorial/feed/ 0
Mongodb Aggregate Example Tutorial https://appdividend.com/2018/10/25/mongodb-aggregate-example-tutorial/ https://appdividend.com/2018/10/25/mongodb-aggregate-example-tutorial/#comments Thu, 25 Oct 2018 16:11:09 +0000 http://localhost/wordpress/?p=1982 Aggrgation in MongoDB Tutorial With Example

Mongodb Aggregate Example Tutorial is today’s leading topic. When it’s time to gather the metrics from MongoDB, there is no better solution than MongoDB aggregations. Aggregations are the set of functions that allow you to manipulate the data being returned from a MongoDB query. Aggregations operations can process the data records and return the computed results. Aggregation operations group […]

The post Mongodb Aggregate Example Tutorial appeared first on AppDividend.

]]>
Aggrgation in MongoDB Tutorial With Example

Mongodb Aggregate Example Tutorial is today’s leading topic. When it’s time to gather the metrics from MongoDB, there is no better solution than MongoDB aggregations. Aggregations are the set of functions that allow you to manipulate the data being returned from a MongoDB query. Aggregations operations can process the data records and return the computed results. Aggregation operations group values from multiple documents together and can perform a variety of activities on the grouped data to return the single result. Aggregation bundles the data from multiple records and operates in many ways on those pooled data to return one combined result.

Want to learn to code, gain a new skill and get a new job. Check out this amazing program

Mongodb Aggregate Example Tutorial

Aggregate function groups the records in the collection, and can be used to provide the total number(sum), average(avg), minimum(min), maximum(max), etc. out of the group selected.

If we want to perform the aggregate function in MongoDB, The aggregate() is the function to be used. Following is the syntax for aggregation:

db.collection_name.aggregate(aggregate_operation)

Now, let us take an example to understand the whole scenario.

#1: Install MongoDB on Mac

You can install MongoDB using homebrew using the following command.

brew install mongodb

After downloading Mongo, create the “db” directory. The db is the directory where the Mongo data files will live. You can create the folder in the default location by running the mkdir -p /data/db. Make sure that the /data/db directory has the right permissions.

You can start the mongodb daemon using the following command.

mongod

 

Mongodb Aggregate Example Tutorial

Now, run the MongoShell using the following command. Please keep open the MongoDB server and open the new tab of the terminal and type the following command.

mongo

 

MongoDB Aggregation Example

#2: Let us create a database and create a collection.

We need to type the following queries inside the newly opened mongo shell terminal and not the mongo server. Type the following command to create a MongoDB database.

use myaggregate

Now, it will create a new database and if existing then switch to that database.

Next step is to create a mongo collection using the following command.

db.createCollection("stocks")

It will create a collection called stocks. Insert the values inside the collection stocks. Type the following query inside the mongo shell.

db.stocks.insertMany([
   { name: "Infosys", qty: 100, price: 800 },
   { name: "TCS", qty: 100, price: 2000 },
   { name: "Wipro", qty: 2500, price: 300 }
])

It will insert the three documents inside the stocks collection.

Now, we can fetch all the documents using the following query.

db.stocks.find().pretty()

You can verify that we have successfully inserted the multiple data in the stocks collection.

#3: Mongodb Matching Documents

The first stage of a pipeline is matching, and that allows to filter out the documents so that we are only manipulating the documents that we care about. The matching expression looks and acts much like the MongoDB find function or the SQL WHERE clause.

db.stocks.aggregate([
  { $match: { "price": 2000 } }
])

 

Mongodb Matching Documents

This will return the array of stocks that has price 2000. We can use the match stage in this way is no different from using the find method on the collection. Also, take another example of Match documents.

db.stocks.aggregate([ { $match: { "name": "Infosys" } } ]).pretty()
{
	"_id" : ObjectId("5bd1a3839faa94f4a8a40920"),
	"name" : "Infosys",
	"qty" : 100,
	"price" : 800
}

#4: MongoDB Grouping Documents

Once we’ve filtered out the records we don’t want, we can start grouping together the ones that we do into useful subsets. We can also use groups to perform the operations across the common field in all documents, such as calculating the sum of a set of transactions and counting documents.

db.stocks.aggregate([{$group : {_id : "$qty", same_qty : {$sum : 1}}}])

In the above query, we will group those documents which have the same quantities. So it will give us the total number of documents which has the same quantities.

db.stocks.aggregate([{$group : {_id : "$qty", same_qty : {$sum : 1}}}])
{ "_id" : 2500, "same_qty" : 1 }
{ "_id" : 100, "same_qty" : 2 }

The equivalent SQL is following.

SELECT qty, SUM(qty) AS total
       FROM stocks
       GROUP BY same_qty

Different expressions used by an Aggregate function

Expression Description
$sum Add the defined values from all the documents in the collection.
$avg It calculates the average values from all the documents in the collection.
$min It returns the minimum of all values of documents in the collection.
$max It returns the maximum of all values of documents in the collection.
$addToSet Insert values to an array but no duplicates in the resulting document.
$push Insert values to an array in the resulting document.
$first Return the first document from the source document.
$last Return the last document from the source document.

#5: Add sorting with a $sort

The $sort takes a document that specifies the field(s) to sort by and the respective sort order. <sort order>Can have one of the following values:

  • 1 to specify the ascending order.
  • -1 to specify descending order.
  • { $meta: "textScore" }To sort by the computed textScore metadata in descending order. See Metadata Sort for example.
db.stocks.aggregate([
  { $group : {_id : "$qty", total : { $sum : 1 } } },
  { $sort : {total : -1} }
]);

 

MongoDB document sorting

Finally, Mongodb Aggregate Example Tutorial is over.

The post Mongodb Aggregate Example Tutorial appeared first on AppDividend.

]]>
https://appdividend.com/2018/10/25/mongodb-aggregate-example-tutorial/feed/ 2