MongoDB – Map Reduce ”; Previous Next As per the MongoDB documentation, Map-reduce is a data processing paradigm for condensing large volumes of data into useful aggregated results. MongoDB uses mapReduce command for map-reduce operations. MapReduce is generally used for processing large data sets. MapReduce Command Following is the syntax of the basic mapReduce command − >db.collection.mapReduce( function() {emit(key,value);}, //map function function(key,values) {return reduceFunction}, { //reduce function out: collection, query: document, sort: document, limit: number } ) The map-reduce function first queries the collection, then maps the result documents to emit key-value pairs, which is then reduced based on the keys that have multiple values. In the above syntax − map is a javascript function that maps a value with a key and emits a key-value pair reduce is a javascript function that reduces or groups all the documents having the same key out specifies the location of the map-reduce query result query specifies the optional selection criteria for selecting documents sort specifies the optional sort criteria limit specifies the optional maximum number of documents to be returned Using MapReduce Consider the following document structure storing user posts. The document stores user_name of the user and the status of post. { “post_text”: “tutorialspoint is an awesome website for tutorials”, “user_name”: “mark”, “status”:”active” } Now, we will use a mapReduce function on our posts collection to select all the active posts, group them on the basis of user_name and then count the number of posts by each user using the following code − >db.posts.mapReduce( function() { emit(this.user_id,1); }, function(key, values) {return Array.sum(values)}, { query:{status:”active”}, out:”post_total” } ) The above mapReduce query outputs the following result − { “result” : “post_total”, “timeMillis” : 9, “counts” : { “input” : 4, “emit” : 4, “reduce” : 2, “output” : 2 }, “ok” : 1, } The result shows that a total of 4 documents matched the query (status:”active”), the map function emitted 4 documents with key-value pairs and finally the reduce function grouped mapped documents having the same keys into 2. To see the result of this mapReduce query, use the find operator − >db.posts.mapReduce( function() { emit(this.user_id,1); }, function(key, values) {return Array.sum(values)}, { query:{status:”active”}, out:”post_total” } ).find() The above query gives the following result which indicates that both users tom and mark have two posts in active states − { “_id” : “tom”, “value” : 2 } { “_id” : “mark”, “value” : 2 } In a similar manner, MapReduce queries can be used to construct large complex aggregation queries. The use of custom Javascript functions make use of MapReduce which is very flexible and powerful. Print Page Previous Next Advertisements ”;
Category: mongodb
MongoDB – Advanced Indexing
MongoDB – Advanced Indexing ”; Previous Next we have inserted the following document in the collection named users as shown below − db.users.insert( { “address”: { “city”: “Los Angeles”, “state”: “California”, “pincode”: “123” }, “tags”: [ “music”, “cricket”, “blogs” ], “name”: “Tom Benzamin” } ) The above document contains an address sub-document and a tags array. Indexing Array Fields Suppose we want to search user documents based on the user’s tags. For this, we will create an index on tags array in the collection. Creating an index on array in turn creates separate index entries for each of its fields. So in our case when we create an index on tags array, separate indexes will be created for its values music, cricket and blogs. To create an index on tags array, use the following code − >db.users.createIndex({“tags”:1}) { “createdCollectionAutomatically” : false, “numIndexesBefore” : 2, “numIndexesAfter” : 3, “ok” : 1 } > After creating the index, we can search on the tags field of the collection like this − > db.users.find({tags:”cricket”}).pretty() { “_id” : ObjectId(“5dd7c927f1dd4583e7103fdf”), “address” : { “city” : “Los Angeles”, “state” : “California”, “pincode” : “123” }, “tags” : [ “music”, “cricket”, “blogs” ], “name” : “Tom Benzamin” } > To verify that proper indexing is used, use the following explain command − >db.users.find({tags:”cricket”}).explain() This gives you the following result − { “queryPlanner” : { “plannerVersion” : 1, “namespace” : “mydb.users”, “indexFilterSet” : false, “parsedQuery” : { “tags” : { “$eq” : “cricket” } }, “queryHash” : “9D3B61A7”, “planCacheKey” : “04C9997B”, “winningPlan” : { “stage” : “FETCH”, “inputStage” : { “stage” : “IXSCAN”, “keyPattern” : { “tags” : 1 }, “indexName” : “tags_1”, “isMultiKey” : false, “multiKeyPaths” : { “tags” : [ ] }, “isUnique” : false, “isSparse” : false, “isPartial” : false, “indexVersion” : 2, “direction” : “forward”, “indexBounds” : { “tags” : [ “[“cricket”, “cricket”]” ] } } }, “rejectedPlans” : [ ] }, “serverInfo” : { “host” : “Krishna”, “port” : 27017, “version” : “4.2.1”, “gitVersion” : “edf6d45851c0b9ee15548f0f847df141764a317e” }, “ok” : 1 } > The above command resulted in “cursor” : “BtreeCursor tags_1” which confirms that proper indexing is used. Indexing Sub-Document Fields Suppose that we want to search documents based on city, state and pincode fields. Since all these fields are part of address sub-document field, we will create an index on all the fields of the sub-document. For creating an index on all the three fields of the sub-document, use the following code − >db.users.createIndex({“address.city”:1,”address.state”:1,”address.pincode”:1}) { “numIndexesBefore” : 4, “numIndexesAfter” : 4, “note” : “all indexes already exist”, “ok” : 1 } > Once the index is created, we can search for any of the sub-document fields utilizing this index as follows − > db.users.find({“address.city”:”Los Angeles”}).pretty() { “_id” : ObjectId(“5dd7c927f1dd4583e7103fdf”), “address” : { “city” : “Los Angeles”, “state” : “California”, “pincode” : “123” }, “tags” : [ “music”, “cricket”, “blogs” ], “name” : “Tom Benzamin” } Remember that the query expression has to follow the order of the index specified. So the index created above would support the following queries − >db.users.find({“address.city”:”Los Angeles”,”address.state”:”California”}).pretty() { “_id” : ObjectId(“5dd7c927f1dd4583e7103fdf”), “address” : { “city” : “Los Angeles”, “state” : “California”, “pincode” : “123” }, “tags” : [ “music”, “cricket”, “blogs” ], “name” : “Tom Benzamin” } > Print Page Previous Next Advertisements ”;
MongoDB – Regular Expression
MongoDB – Regular Expression ”; Previous Next Regular Expressions are frequently used in all languages to search for a pattern or word in any string. MongoDB also provides functionality of regular expression for string pattern matching using the $regex operator. MongoDB uses PCRE (Perl Compatible Regular Expression) as regular expression language. Unlike text search, we do not need to do any configuration or command to use regular expressions. Assume we have inserted a document in a database named posts as shown below − > db.posts.insert( { “post_text”: “enjoy the mongodb articles on tutorialspoint”, “tags”: [ “mongodb”, “tutorialspoint” ] } WriteResult({ “nInserted” : 1 }) Using regex Expression The following regex query searches for all the posts containing string tutorialspoint in it − > db.posts.find({post_text:{$regex:”tutorialspoint”}}).pretty() { “_id” : ObjectId(“5dd7ce28f1dd4583e7103fe0”), “post_text” : “enjoy the mongodb articles on tutorialspoint”, “tags” : [ “mongodb”, “tutorialspoint” ] } { “_id” : ObjectId(“5dd7d111f1dd4583e7103fe2”), “post_text” : “enjoy the mongodb articles on tutorialspoint”, “tags” : [ “mongodb”, “tutorialspoint” ] } > The same query can also be written as − >db.posts.find({post_text:/tutorialspoint/}) Using regex Expression with Case Insensitive To make the search case insensitive, we use the $options parameter with value $i. The following command will look for strings having the word tutorialspoint, irrespective of smaller or capital case − >db.posts.find({post_text:{$regex:”tutorialspoint”,$options:”$i”}}) One of the results returned from this query is the following document which contains the word tutorialspoint in different cases − { “_id” : ObjectId(“53493d37d852429c10000004”), “post_text” : “hey! this is my post on TutorialsPoint”, “tags” : [ “tutorialspoint” ] } Using regex for Array Elements We can also use the concept of regex on array field. This is particularly very important when we implement the functionality of tags. So, if you want to search for all the posts having tags beginning from the word tutorial (either tutorial or tutorials or tutorialpoint or tutorialphp), you can use the following code − >db.posts.find({tags:{$regex:”tutorial”}}) Optimizing Regular Expression Queries If the document fields are indexed, the query will use make use of indexed values to match the regular expression. This makes the search very fast as compared to the regular expression scanning the whole collection. If the regular expression is a prefix expression, all the matches are meant to start with a certain string characters. For e.g., if the regex expression is ^tut, then the query has to search for only those strings that begin with tut. Print Page Previous Next Advertisements ”;
MongoDB – Analyzing Queries
MongoDB – Analyzing Queries ”; Previous Next Analyzing queries is a very important aspect of measuring how effective the database and indexing design is. We will learn about the frequently used $explain and $hint queries. Using $explain The $explain operator provides information on the query, indexes used in a query and other statistics. It is very useful when analyzing how well your indexes are optimized. In the last chapter, we had already created an index for the users collection on fields gender and user_name using the following query − >db.users.createIndex({gender:1,user_name:1}) { “numIndexesBefore” : 2, “numIndexesAfter” : 2, “note” : “all indexes already exist”, “ok” : 1 } We will now use $explain on the following query − >db.users.find({gender:”M”},{user_name:1,_id:0}).explain() The above explain() query returns the following analyzed result − { “queryPlanner” : { “plannerVersion” : 1, “namespace” : “mydb.users”, “indexFilterSet” : false, “parsedQuery” : { “gender” : { “$eq” : “M” } }, “queryHash” : “B4037D3C”, “planCacheKey” : “DEAAE17C”, “winningPlan” : { “stage” : “PROJECTION_COVERED”, “transformBy” : { “user_name” : 1, “_id” : 0 }, “inputStage” : { “stage” : “IXSCAN”, “keyPattern” : { “gender” : 1, “user_name” : 1 }, “indexName” : “gender_1_user_name_1”, “isMultiKey” : false, “multiKeyPaths” : { “gender” : [ ], “user_name” : [ ] }, “isUnique” : false, “isSparse” : false, “isPartial” : false, “indexVersion” : 2, “direction” : “forward”, “indexBounds” : { “gender” : [ “[“M”, “M”]” ], “user_name” : [ “[MinKey, MaxKey]” ] } } }, “rejectedPlans” : [ ] }, “serverInfo” : { “host” : “Krishna”, “port” : 27017, “version” : “4.2.1”, “gitVersion” : “edf6d45851c0b9ee15548f0f847df141764a317e” }, “ok” : 1 } We will now look at the fields in this result set − The true value of indexOnly indicates that this query has used indexing. The cursor field specifies the type of cursor used. BTreeCursor type indicates that an index was used and also gives the name of the index used. BasicCursor indicates that a full scan was made without using any indexes. n indicates the number of documents matching returned. nscannedObjects indicates the total number of documents scanned. nscanned indicates the total number of documents or index entries scanned. Using $hint The $hint operator forces the query optimizer to use the specified index to run a query. This is particularly useful when you want to test performance of a query with different indexes. For example, the following query specifies the index on fields gender and user_name to be used for this query − >db.users.find({gender:”M”},{user_name:1,_id:0}).hint({gender:1,user_name:1}) { “user_name” : “tombenzamin” } To analyze the above query using $explain − >db.users.find({gender:”M”},{user_name:1,_id:0}).hint({gender:1,user_name:1}).explain() Which gives you the following result − { “queryPlanner” : { “plannerVersion” : 1, “namespace” : “mydb.users”, “indexFilterSet” : false, “parsedQuery” : { “gender” : { “$eq” : “M” } }, “queryHash” : “B4037D3C”, “planCacheKey” : “DEAAE17C”, “winningPlan” : { “stage” : “PROJECTION_COVERED”, “transformBy” : { “user_name” : 1, “_id” : 0 }, “inputStage” : { “stage” : “IXSCAN”, “keyPattern” : { “gender” : 1, “user_name” : 1 }, “indexName” : “gender_1_user_name_1”, “isMultiKey” : false, “multiKeyPaths” : { “gender” : [ ], “user_name” : [ ] }, “isUnique” : false, “isSparse” : false, “isPartial” : false, “indexVersion” : 2, “direction” : “forward”, “indexBounds” : { “gender” : [ “[“M”, “M”]” ], “user_name” : [ “[MinKey, MaxKey]” ] } } }, “rejectedPlans” : [ ] }, “serverInfo” : { “host” : “Krishna”, “port” : 27017, “version” : “4.2.1”, 109 “gitVersion” : “edf6d45851c0b9ee15548f0f847df141764a317e” }, “ok” : 1 } Print Page Previous Next Advertisements ”;
MongoDB – Create Backup
MongoDB – Create Backup ”; Previous Next In this chapter, we will see how to create a backup in MongoDB. Dump MongoDB Data To create backup of database in MongoDB, you should use mongodump command. This command will dump the entire data of your server into the dump directory. There are many options available by which you can limit the amount of data or create backup of your remote server. Syntax The basic syntax of mongodump command is as follows − >mongodump Example Start your mongod server. Assuming that your mongod server is running on the localhost and port 27017, open a command prompt and go to the bin directory of your mongodb instance and type the command mongodump Consider the mycol collection has the following data. >mongodump The command will connect to the server running at 127.0.0.1 and port 27017 and back all data of the server to directory /bin/dump/. Following is the output of the command − Following is a list of available options that can be used with the mongodump command. Syntax Description Example mongodump –host HOST_NAME –port PORT_NUMBER This commmand will backup all databases of specified mongod instance. mongodump –host tutorialspoint.com –port 27017 mongodump –dbpath DB_PATH –out BACKUP_DIRECTORY This command will backup only specified database at specified path. mongodump –dbpath /data/db/ –out /data/backup/ mongodump –collection COLLECTION –db DB_NAME This command will backup only specified collection of specified database. mongodump –collection mycol –db test Restore data To restore backup data MongoDB”s mongorestore command is used. This command restores all of the data from the backup directory. Syntax The basic syntax of mongorestore command is − >mongorestore Following is the output of the command − Print Page Previous Next Advertisements ”;
MongoDB – Deployment
MongoDB – Deployment ”; Previous Next When you are preparing a MongoDB deployment, you should try to understand how your application is going to hold up in production. It’s a good idea to develop a consistent, repeatable approach to managing your deployment environment so that you can minimize any surprises once you’re in production. The best approach incorporates prototyping your set up, conducting load testing, monitoring key metrics, and using that information to scale your set up. The key part of the approach is to proactively monitor your entire system – this will help you understand how your production system will hold up before deploying, and determine where you will need to add capacity. Having insight into potential spikes in your memory usage, for example, could help put out a write-lock fire before it starts. To monitor your deployment, MongoDB provides some of the following commands − mongostat This command checks the status of all running mongod instances and return counters of database operations. These counters include inserts, queries, updates, deletes, and cursors. Command also shows when you’re hitting page faults, and showcase your lock percentage. This means that you”re running low on memory, hitting write capacity or have some performance issue. To run the command, start your mongod instance. In another command prompt, go to bin directory of your mongodb installation and type mongostat. D:set upmongodbbin>mongostat Following is the output of the command − mongotop This command tracks and reports the read and write activity of MongoDB instance on a collection basis. By default, mongotop returns information in each second, which you can change it accordingly. You should check that this read and write activity matches your application intention, and you’re not firing too many writes to the database at a time, reading too frequently from a disk, or are exceeding your working set size. To run the command, start your mongod instance. In another command prompt, go to bin directory of your mongodb installation and type mongotop. D:set upmongodbbin>mongotop Following is the output of the command − To change mongotop command to return information less frequently, specify a specific number after the mongotop command. D:set upmongodbbin>mongotop 30 The above example will return values every 30 seconds. Apart from the MongoDB tools, 10gen provides a free, hosted monitoring service, MongoDB Management Service (MMS), that provides a dashboard and gives you a view of the metrics from your entire cluster. Print Page Previous Next Advertisements ”;
MongoDB – Sharding
MongoDB – Sharding ”; Previous Next Sharding is the process of storing data records across multiple machines and it is MongoDB”s approach to meeting the demands of data growth. As the size of the data increases, a single machine may not be sufficient to store the data nor provide an acceptable read and write throughput. Sharding solves the problem with horizontal scaling. With sharding, you add more machines to support data growth and the demands of read and write operations. Why Sharding? In replication, all writes go to master node Latency sensitive queries still go to master Single replica set has limitation of 12 nodes Memory can”t be large enough when active dataset is big Local disk is not big enough Vertical scaling is too expensive Sharding in MongoDB The following diagram shows the Sharding in MongoDB using sharded cluster. In the following diagram, there are three main components − Shards − Shards are used to store data. They provide high availability and data consistency. In production environment, each shard is a separate replica set. Config Servers − Config servers store the cluster”s metadata. This data contains a mapping of the cluster”s data set to the shards. The query router uses this metadata to target operations to specific shards. In production environment, sharded clusters have exactly 3 config servers. Query Routers − Query routers are basically mongo instances, interface with client applications and direct operations to the appropriate shard. The query router processes and targets the operations to shards and then returns results to the clients. A sharded cluster can contain more than one query router to divide the client request load. A client sends requests to one query router. Generally, a sharded cluster have many query routers. Print Page Previous Next Advertisements ”;
MongoDB – Java
MongoDB – Java ”; Previous Next In this chapter, we will learn how to set up MongoDB CLIENT. Installation Before you start using MongoDB in your Java programs, you need to make sure that you have MongoDB CLIENT and Java set up on the machine. You can check Java tutorial for Java installation on your machine. Now, let us check how to set up MongoDB CLIENT. You need to download the jar mongodb-driver-3.11.2.jar and its dependency mongodb-driver-core-3.11.2.jar.. Make sure to download the latest release of these jar files. You need to include the downloaded jar files into your classpath. Connect to Database To connect database, you need to specify the database name, if the database doesn”t exist then MongoDB creates it automatically. Following is the code snippet to connect to the database − import com.mongodb.client.MongoDatabase; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; public class ConnectToDB { public static void main( String args[] ) { // Creating a Mongo client MongoClient mongo = new MongoClient( “localhost” , 27017 ); // Creating Credentials MongoCredential credential; credential = MongoCredential.createCredential(“sampleUser”, “myDb”, “password”.toCharArray()); System.out.println(“Connected to the database successfully”); // Accessing the database MongoDatabase database = mongo.getDatabase(“myDb”); System.out.println(“Credentials ::”+ credential); } } Now, let”s compile and run the above program to create our database myDb as shown below. $javac ConnectToDB.java $java ConnectToDB On executing, the above program gives you the following output. Connected to the database successfully Credentials ::MongoCredential{ mechanism = null, userName = ”sampleUser”, source = ”myDb”, password = <hidden>, mechanismProperties = {} } Create a Collection To create a collection, createCollection() method of com.mongodb.client.MongoDatabase class is used. Following is the code snippet to create a collection − import com.mongodb.client.MongoDatabase; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; public class CreatingCollection { public static void main( String args[] ) { // Creating a Mongo client MongoClient mongo = new MongoClient( “localhost” , 27017 ); // Creating Credentials MongoCredential credential; credential = MongoCredential.createCredential(“sampleUser”, “myDb”, “password”.toCharArray()); System.out.println(“Connected to the database successfully”); //Accessing the database MongoDatabase database = mongo.getDatabase(“myDb”); //Creating a collection database.createCollection(“sampleCollection”); System.out.println(“Collection created successfully”); } } On compiling, the above program gives you the following result − Connected to the database successfully Collection created successfully Getting/Selecting a Collection To get/select a collection from the database, getCollection() method of com.mongodb.client.MongoDatabase class is used. Following is the program to get/select a collection − import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; public class selectingCollection { public static void main( String args[] ) { // Creating a Mongo client MongoClient mongo = new MongoClient( “localhost” , 27017 ); // Creating Credentials MongoCredential credential; credential = MongoCredential.createCredential(“sampleUser”, “myDb”, “password”.toCharArray()); System.out.println(“Connected to the database successfully”); // Accessing the database MongoDatabase database = mongo.getDatabase(“myDb”); // Creating a collection System.out.println(“Collection created successfully”); // Retrieving a collection MongoCollection<Document> collection = database.getCollection(“myCollection”); System.out.println(“Collection myCollection selected successfully”); } } On compiling, the above program gives you the following result − Connected to the database successfully Collection created successfully Collection myCollection selected successfully Insert a Document To insert a document into MongoDB, insert() method of com.mongodb.client.MongoCollection class is used. Following is the code snippet to insert a document − import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import org.bson.Document; import com.mongodb.MongoClient; public class InsertingDocument { public static void main( String args[] ) { // Creating a Mongo client MongoClient mongo = new MongoClient( “localhost” , 27017 ); // Accessing the database MongoDatabase database = mongo.getDatabase(“myDb”); // Creating a collection database.createCollection(“sampleCollection”); System.out.println(“Collection created successfully”); // Retrieving a collection MongoCollection<Document> collection = database.getCollection(“sampleCollection”); System.out.println(“Collection sampleCollection selected successfully”); Document document = new Document(“title”, “MongoDB”) .append(“description”, “database”) .append(“likes”, 100) .append(“url”, “http://www.tutorialspoint.com/mongodb/”) .append(“by”, “tutorials point”); //Inserting document into the collection collection.insertOne(document); System.out.println(“Document inserted successfully”); } On compiling, the above program gives you the following result − Connected to the database successfully Collection sampleCollection selected successfully Document inserted successfully Retrieve All Documents To select all documents from the collection, find() method of com.mongodb.client.MongoCollection class is used. This method returns a cursor, so you need to iterate this cursor. Following is the program to select all documents − import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; public class RetrievingAllDocuments { public static void main( String args[] ) { // Creating a Mongo client MongoClient mongo = new MongoClient( “localhost” , 27017 ); // Creating Credentials MongoCredential credential; credential = MongoCredential.createCredential(“sampleUser”, “myDb”, “password”.toCharArray()); System.out.println(“Connected to the database successfully”); // Accessing the database MongoDatabase database = mongo.getDatabase(“myDb”); // Retrieving a collection MongoCollection<Document> collection = database.getCollection(“sampleCollection”); System.out.println(“Collection sampleCollection selected successfully”); Document document1 = new Document(“title”, “MongoDB”) .append(“description”, “database”) .append(“likes”, 100) .append(“url”, “http://www.tutorialspoint.com/mongodb/”) .append(“by”, “tutorials point”); Document document2 = new Document(“title”, “RethinkDB”) .append(“description”, “database”) .append(“likes”, 200) .append(“url”, “http://www.tutorialspoint.com/rethinkdb/”) .append(“by”, “tutorials point”); List<Document> list = new ArrayList<Document>(); list.add(document1); list.add(document2); collection.insertMany(list); // Getting the iterable object FindIterable<Document> iterDoc = collection.find(); int i = 1; // Getting the iterator Iterator it = iterDoc.iterator(); while (it.hasNext()) { System.out.println(it.next()); i++; } } } On compiling, the above program gives you the following result − Connected to the database successfully Collection sampleCollection selected successfully Document{{_id=5dce4e9ff68a9c2449e197b2, title=MongoDB, description=database, likes=100, url=http://www.tutorialspoint.com/mongodb/, by=tutorials point}} Document{{_id=5dce4e9ff68a9c2449e197b3, title=RethinkDB, description=database, likes=200, url=http://www.tutorialspoint.com/rethinkdb/, by=tutorials point}} Update Document To update a document from the collection, updateOne() method of com.mongodb.client.MongoCollection class is used. Following is the program to select the first document − import com.mongodb.client.FindIterable; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoDatabase; import com.mongodb.client.model.Filters; import com.mongodb.client.model.Updates; import java.util.Iterator; import org.bson.Document; import com.mongodb.MongoClient; import com.mongodb.MongoCredential; public class UpdatingDocuments { public static void main( String args[] ) { // Creating a Mongo client MongoClient mongo = new MongoClient( “localhost” , 27017 ); // Creating Credentials MongoCredential credential; credential = MongoCredential.createCredential(“sampleUser”, “myDb”, “password”.toCharArray()); System.out.println(“Connected to the database successfully”); // Accessing the database MongoDatabase database = mongo.getDatabase(“myDb”); // Retrieving a collection MongoCollection<Document> collection = database.getCollection(“sampleCollection”); System.out.println(“Collection myCollection selected successfully”); collection.updateOne(Filters.eq(“title”, 1), Updates.set(“likes”, 150)); System.out.println(“Document update successfully…”); // Retrieving the documents after updation // Getting the iterable object FindIterable<Document> iterDoc = collection.find(); int i = 1; // Getting the iterator Iterator it = iterDoc.iterator(); while (it.hasNext()) { System.out.println(it.next()); i++; } } } On compiling, the above program gives you the following result − Connected to the
MongoDB – Covered Queries
MongoDB – Covered Queries ”; Previous Next In this chapter, we will learn about covered queries. What is a Covered Query? As per the official MongoDB documentation, a covered query is a query in which − All the fields in the query are part of an index. All the fields returned in the query are in the same index. Since all the fields present in the query are part of an index, MongoDB matches the query conditions and returns the result using the same index without actually looking inside the documents. Since indexes are present in RAM, fetching data from indexes is much faster as compared to fetching data by scanning documents. Using Covered Queries To test covered queries, consider the following document in the users collection − { “_id”: ObjectId(“53402597d852426020000003”), “contact”: “987654321”, “dob”: “01-01-1991”, “gender”: “M”, “name”: “Tom Benzamin”, “user_name”: “tombenzamin” } We will first create a compound index for the users collection on the fields gender and user_name using the following query − >db.users.createIndex({gender:1,user_name:1}) { “createdCollectionAutomatically” : false, “numIndexesBefore” : 1, “numIndexesAfter” : 2, “ok” : 1 } Now, this index will cover the following query − >db.users.find({gender:”M”},{user_name:1,_id:0}) { “user_name” : “tombenzamin” } That is to say that for the above query, MongoDB would not go looking into database documents. Instead it would fetch the required data from indexed data which is very fast. Since our index does not include _id field, we have explicitly excluded it from result set of our query, as MongoDB by default returns _id field in every query. So the following query would not have been covered inside the index created above − >db.users.find({gender:”M”},{user_name:1}) { “_id” : ObjectId(“53402597d852426020000003”), “user_name” : “tombenzamin” } Lastly, remember that an index cannot cover a query if − Any of the indexed fields is an array Any of the indexed fields is a subdocument Print Page Previous Next Advertisements ”;
MongoDB – Database References ”; Previous Next As seen in the last chapter of MongoDB relationships, to implement a normalized database structure in MongoDB, we use the concept of Referenced Relationships also referred to as Manual References in which we manually store the referenced document”s id inside other document. However, in cases where a document contains references from different collections, we can use MongoDB DBRefs. DBRefs vs Manual References As an example scenario, where we would use DBRefs instead of manual references, consider a database where we are storing different types of addresses (home, office, mailing, etc.) in different collections (address_home, address_office, address_mailing, etc). Now, when a user collection”s document references an address, it also needs to specify which collection to look into based on the address type. In such scenarios where a document references documents from many collections, we should use DBRefs. Using DBRefs There are three fields in DBRefs − $ref − This field specifies the collection of the referenced document $id − This field specifies the _id field of the referenced document $db − This is an optional field and contains the name of the database in which the referenced document lies Consider a sample user document having DBRef field address as shown in the code snippet − { “_id”:ObjectId(“53402597d852426020000002”), “address”: { “$ref”: “address_home”, “$id”: ObjectId(“534009e4d852427820000002”), “$db”: “tutorialspoint”}, “contact”: “987654321”, “dob”: “01-01-1991”, “name”: “Tom Benzamin” } The address DBRef field here specifies that the referenced address document lies in address_home collection under tutorialspoint database and has an id of 534009e4d852427820000002. The following code dynamically looks in the collection specified by $ref parameter (address_home in our case) for a document with id as specified by $id parameter in DBRef. >var user = db.users.findOne({“name”:”Tom Benzamin”}) >var dbRef = user.address >db[dbRef.$ref].findOne({“_id”:(dbRef.$id)}) The above code returns the following address document present in address_home collection − { “_id” : ObjectId(“534009e4d852427820000002”), “building” : “22 A, Indiana Apt”, “pincode” : 123456, “city” : “Los Angeles”, “state” : “California” } Print Page Previous Next Advertisements ”;