MongoDB – Query Document

MongoDB – Query Document ”; Previous Next In this chapter, we will learn how to query document from MongoDB collection. The find() Method To query data from MongoDB collection, you need to use MongoDB”s find() method. Syntax The basic syntax of find() method is as follows − >db.COLLECTION_NAME.find() find() method will display all the documents in a non-structured way. Example Assume we have created a collection named mycol as − > use sampleDB switched to db sampleDB > db.createCollection(“mycol”) { “ok” : 1 } > And inserted 3 documents in it using the insert() method as shown below − > db.mycol.insert([ { title: “MongoDB Overview”, description: “MongoDB is no SQL database”, by: “tutorials point”, url: “http://www.tutorialspoint.com”, tags: [“mongodb”, “database”, “NoSQL”], likes: 100 }, { title: “NoSQL Database”, description: “NoSQL database doesn”t have tables”, by: “tutorials point”, url: “http://www.tutorialspoint.com”, tags: [“mongodb”, “database”, “NoSQL”], likes: 20, comments: [ { user:”user1″, message: “My first comment”, dateCreated: new Date(2013,11,10,2,35), like: 0 } ] } ]) Following method retrieves all the documents in the collection − > db.mycol.find() { “_id” : ObjectId(“5dd4e2cc0821d3b44607534c”), “title” : “MongoDB Overview”, “description” : “MongoDB is no SQL database”, “by” : “tutorials point”, “url” : “http://www.tutorialspoint.com”, “tags” : [ “mongodb”, “database”, “NoSQL” ], “likes” : 100 } { “_id” : ObjectId(“5dd4e2cc0821d3b44607534d”), “title” : “NoSQL Database”, “description” : “NoSQL database doesn”t have tables”, “by” : “tutorials point”, “url” : “http://www.tutorialspoint.com”, “tags” : [ “mongodb”, “database”, “NoSQL” ], “likes” : 20, “comments” : [ { “user” : “user1”, “message” : “My first comment”, “dateCreated” : ISODate(“2013-12-09T21:05:00Z”), “like” : 0 } ] } > The pretty() Method To display the results in a formatted way, you can use pretty() method. Syntax >db.COLLECTION_NAME.find().pretty() Example Following example retrieves all the documents from the collection named mycol and arranges them in an easy-to-read format. > db.mycol.find().pretty() { “_id” : ObjectId(“5dd4e2cc0821d3b44607534c”), “title” : “MongoDB Overview”, “description” : “MongoDB is no SQL database”, “by” : “tutorials point”, “url” : “http://www.tutorialspoint.com”, “tags” : [ “mongodb”, “database”, “NoSQL” ], “likes” : 100 } { “_id” : ObjectId(“5dd4e2cc0821d3b44607534d”), “title” : “NoSQL Database”, “description” : “NoSQL database doesn”t have tables”, “by” : “tutorials point”, “url” : “http://www.tutorialspoint.com”, “tags” : [ “mongodb”, “database”, “NoSQL” ], “likes” : 20, “comments” : [ { “user” : “user1”, “message” : “My first comment”, “dateCreated” : ISODate(“2013-12-09T21:05:00Z”), “like” : 0 } ] } The findOne() method Apart from the find() method, there is findOne() method, that returns only one document. Syntax >db.COLLECTIONNAME.findOne() Example Following example retrieves the document with title MongoDB Overview. > db.mycol.findOne({title: “MongoDB Overview”}) { “_id” : ObjectId(“5dd6542170fb13eec3963bf0”), “title” : “MongoDB Overview”, “description” : “MongoDB is no SQL database”, “by” : “tutorials point”, “url” : “http://www.tutorialspoint.com”, “tags” : [ “mongodb”, “database”, “NoSQL” ], “likes” : 100 } RDBMS Where Clause Equivalents in MongoDB To query the document on the basis of some condition, you can use following operations. Operation Syntax Example RDBMS Equivalent Equality {<key>:{$eg;<value>}} db.mycol.find({“by”:”tutorials point”}).pretty() where by = ”tutorials point” Less Than {<key>:{$lt:<value>}} db.mycol.find({“likes”:{$lt:50}}).pretty() where likes < 50 Less Than Equals {<key>:{$lte:<value>}} db.mycol.find({“likes”:{$lte:50}}).pretty() where likes <= 50 Greater Than {<key>:{$gt:<value>}} db.mycol.find({“likes”:{$gt:50}}).pretty() where likes > 50 Greater Than Equals {<key>:{$gte:<value>}} db.mycol.find({“likes”:{$gte:50}}).pretty() where likes >= 50 Not Equals {<key>:{$ne:<value>}} db.mycol.find({“likes”:{$ne:50}}).pretty() where likes != 50 Values in an array {<key>:{$in:[<value1>, <value2>,……<valueN>]}} db.mycol.find({“name”:{$in:[“Raj”, “Ram”, “Raghu”]}}).pretty() Where name matches any of the value in :[“Raj”, “Ram”, “Raghu”] Values not in an array {<key>:{$nin:<value>}} db.mycol.find({“name”:{$nin:[“Ramu”, “Raghav”]}}).pretty() Where name values is not in the array :[“Ramu”, “Raghav”] or, doesn’t exist at all AND in MongoDB Syntax To query documents based on the AND condition, you need to use $and keyword. Following is the basic syntax of AND − >db.mycol.find({ $and: [ {<key1>:<value1>}, { <key2>:<value2>} ] }) Example Following example will show all the tutorials written by ”tutorials point” and whose title is ”MongoDB Overview”. > db.mycol.find({$and:[{“by”:”tutorials point”},{“title”: “MongoDB Overview”}]}).pretty() { “_id” : ObjectId(“5dd4e2cc0821d3b44607534c”), “title” : “MongoDB Overview”, “description” : “MongoDB is no SQL database”, “by” : “tutorials point”, “url” : “http://www.tutorialspoint.com”, “tags” : [ “mongodb”, “database”, “NoSQL” ], “likes” : 100 } > For the above given example, equivalent where clause will be ” where by = ”tutorials point” AND title = ”MongoDB Overview” ”. You can pass any number of key, value pairs in find clause. OR in MongoDB Syntax To query documents based on the OR condition, you need to use $or keyword. Following is the basic syntax of OR − >db.mycol.find( { $or: [ {key1: value1}, {key2:value2} ] } ).pretty() Example Following example will show all the tutorials written by ”tutorials point” or whose title is ”MongoDB Overview”. >db.mycol.find({$or:[{“by”:”tutorials point”},{“title”: “MongoDB Overview”}]}).pretty() { “_id”: ObjectId(7df78ad8902c), “title”: “MongoDB Overview”, “description”: “MongoDB is no sql database”, “by”: “tutorials point”, “url”: “http://www.tutorialspoint.com”, “tags”: [“mongodb”, “database”, “NoSQL”], “likes”: “100” } > Using AND and OR Together Example The following example will show the documents that have likes greater than 10 and whose title is either ”MongoDB Overview” or by is ”tutorials point”. Equivalent SQL where clause is ”where likes>10 AND (by = ”tutorials point” OR title = ”MongoDB Overview”)” >db.mycol.find({“likes”: {$gt:10}, $or: [{“by”: “tutorials point”}, {“title”: “MongoDB Overview”}]}).pretty() { “_id”: ObjectId(7df78ad8902c), “title”: “MongoDB Overview”, “description”: “MongoDB is no sql database”, “by”: “tutorials point”, “url”: “http://www.tutorialspoint.com”, “tags”: [“mongodb”, “database”, “NoSQL”], “likes”: “100” } > NOR in MongoDB Syntax To query documents based on the NOT condition, you need to use $not keyword. Following is the basic syntax of NOT − >db.COLLECTION_NAME.find( { $not: [ {key1: value1}, {key2:value2} ] } ) Example Assume we have inserted 3 documents in the collection empDetails as shown below − db.empDetails.insertMany( [ { First_Name: “Radhika”, Last_Name: “Sharma”, Age: “26”, e_mail: “[email protected]”, phone: “9000012345” }, { First_Name: “Rachel”, Last_Name: “Christopher”, Age: “27”, e_mail: “[email protected]”, phone: “9000054321” }, { First_Name: “Fathima”, Last_Name: “Sheik”, Age: “24”, e_mail: “[email protected]”, phone: “9000054321” } ] ) Following example will retrieve the document(s) whose first name is not “Radhika” and last name is not “Christopher” > db.empDetails.find( { $nor:[ 40 {“First_Name”: “Radhika”}, {“Last_Name”: “Christopher”} ] } ).pretty() { “_id” : ObjectId(“5dd631f270fb13eec3963bef”), “First_Name” : “Fathima”, “Last_Name” : “Sheik”, “Age” : “24”, “e_mail”

MongoDB – Delete Document

MongoDB – Delete Document ”; Previous Next In this chapter, we will learn how to delete a document using MongoDB. The remove() Method MongoDB”s remove() method is used to remove a document from the collection. remove() method accepts two parameters. One is deletion criteria and second is justOne flag. deletion criteria − (Optional) deletion criteria according to documents will be removed. justOne − (Optional) if set to true or 1, then remove only one document. Syntax Basic syntax of remove() method is as follows − >db.COLLECTION_NAME.remove(DELLETION_CRITTERIA) Example Consider the mycol collection has the following data. {_id : ObjectId(“507f191e810c19729de860e1”), title: “MongoDB Overview”}, {_id : ObjectId(“507f191e810c19729de860e2”), title: “NoSQL Overview”}, {_id : ObjectId(“507f191e810c19729de860e3”), title: “Tutorials Point Overview”} Following example will remove all the documents whose title is ”MongoDB Overview”. >db.mycol.remove({”title”:”MongoDB Overview”}) WriteResult({“nRemoved” : 1}) > db.mycol.find() {“_id” : ObjectId(“507f191e810c19729de860e2”), “title” : “NoSQL Overview” } {“_id” : ObjectId(“507f191e810c19729de860e3”), “title” : “Tutorials Point Overview” } Remove Only One If there are multiple records and you want to delete only the first record, then set justOne parameter in remove() method. >db.COLLECTION_NAME.remove(DELETION_CRITERIA,1) Remove All Documents If you don”t specify deletion criteria, then MongoDB will delete whole documents from the collection. This is equivalent of SQL”s truncate command. > db.mycol.remove({}) WriteResult({ “nRemoved” : 2 }) > db.mycol.find() > Print Page Previous Next Advertisements ”;

MongoDB – Indexing

MongoDB – Indexing ”; Previous Next Indexes support the efficient resolution of queries. Without indexes, MongoDB must scan every document of a collection to select those documents that match the query statement. This scan is highly inefficient and require MongoDB to process a large volume of data. Indexes are special data structures, that store a small portion of the data set in an easy-to-traverse form. The index stores the value of a specific field or set of fields, ordered by the value of the field as specified in the index. The createIndex() Method To create an index, you need to use createIndex() method of MongoDB. Syntax The basic syntax of createIndex() method is as follows(). >db.COLLECTION_NAME.createIndex({KEY:1}) Here key is the name of the field on which you want to create index and 1 is for ascending order. To create index in descending order you need to use -1. Example >db.mycol.createIndex({“title”:1}) { “createdCollectionAutomatically” : false, “numIndexesBefore” : 1, “numIndexesAfter” : 2, “ok” : 1 } > In createIndex() method you can pass multiple fields, to create index on multiple fields. >db.mycol.createIndex({“title”:1,”description”:-1}) > This method also accepts list of options (which are optional). Following is the list − Parameter Type Description background Boolean Builds the index in the background so that building an index does not block other database activities. Specify true to build in the background. The default value is false. unique Boolean Creates a unique index so that the collection will not accept insertion of documents where the index key or keys match an existing value in the index. Specify true to create a unique index. The default value is false. name string The name of the index. If unspecified, MongoDB generates an index name by concatenating the names of the indexed fields and the sort order. sparse Boolean If true, the index only references documents with the specified field. These indexes use less space but behave differently in some situations (particularly sorts). The default value is false. expireAfterSeconds integer Specifies a value, in seconds, as a TTL to control how long MongoDB retains documents in this collection. weights document The weight is a number ranging from 1 to 99,999 and denotes the significance of the field relative to the other indexed fields in terms of the score. default_language string For a text index, the language that determines the list of stop words and the rules for the stemmer and tokenizer. The default value is English. language_override string For a text index, specify the name of the field in the document that contains, the language to override the default language. The default value is language. The dropIndex() method You can drop a particular index using the dropIndex() method of MongoDB. Syntax The basic syntax of DropIndex() method is as follows(). >db.COLLECTION_NAME.dropIndex({KEY:1}) Here, “key” is the name of the file on which you want to remove an existing index. Instead of the index specification document (above syntax), you can also specify the name of the index directly as: dropIndex(“name_of_the_index”) Example > db.mycol.dropIndex({“title”:1}) { “ok” : 0, “errmsg” : “can”t find index with key: { title: 1.0 }”, “code” : 27, “codeName” : “IndexNotFound” } The dropIndexes() method This method deletes multiple (specified) indexes on a collection. Syntax The basic syntax of DropIndexes() method is as follows() − >db.COLLECTION_NAME.dropIndexes() Example Assume we have created 2 indexes in the named mycol collection as shown below − > db.mycol.createIndex({“title”:1,”description”:-1}) Following example removes the above created indexes of mycol − >db.mycol.dropIndexes({“title”:1,”description”:-1}) { “nIndexesWas” : 2, “ok” : 1 } > The getIndexes() method This method returns the description of all the indexes int the collection. Syntax Following is the basic syntax od the getIndexes() method − db.COLLECTION_NAME.getIndexes() Example Assume we have created 2 indexes in the named mycol collection as shown below − > db.mycol.createIndex({“title”:1,”description”:-1}) Following example retrieves all the indexes in the collection mycol − > db.mycol.getIndexes() [ { “v” : 2, “key” : { “_id” : 1 }, “name” : “_id_”, “ns” : “test.mycol” }, { “v” : 2, “key” : { “title” : 1, “description” : -1 }, “name” : “title_1_description_-1”, “ns” : “test.mycol” } ] > Print Page Previous Next Advertisements ”;

MongoDB – Replication

MongoDB – Replication ”; Previous Next Replication is the process of synchronizing data across multiple servers. Replication provides redundancy and increases data availability with multiple copies of data on different database servers. Replication protects a database from the loss of a single server. Replication also allows you to recover from hardware failure and service interruptions. With additional copies of the data, you can dedicate one to disaster recovery, reporting, or backup. Why Replication? To keep your data safe High (24*7) availability of data Disaster recovery No downtime for maintenance (like backups, index rebuilds, compaction) Read scaling (extra copies to read from) Replica set is transparent to the application How Replication Works in MongoDB MongoDB achieves replication by the use of replica set. A replica set is a group of mongod instances that host the same data set. In a replica, one node is primary node that receives all write operations. All other instances, such as secondaries, apply operations from the primary so that they have the same data set. Replica set can have only one primary node. Replica set is a group of two or more nodes (generally minimum 3 nodes are required). In a replica set, one node is primary node and remaining nodes are secondary. All data replicates from primary to secondary node. At the time of automatic failover or maintenance, election establishes for primary and a new primary node is elected. After the recovery of failed node, it again join the replica set and works as a secondary node. A typical diagram of MongoDB replication is shown in which client application always interact with the primary node and the primary node then replicates the data to the secondary nodes. Replica Set Features A cluster of N nodes Any one node can be primary All write operations go to primary Automatic failover Automatic recovery Consensus election of primary Set Up a Replica Set In this tutorial, we will convert standalone MongoDB instance to a replica set. To convert to replica set, following are the steps − Shutdown already running MongoDB server. Start the MongoDB server by specifying — replSet option. Following is the basic syntax of –replSet − mongod –port “PORT” –dbpath “YOUR_DB_DATA_PATH” –replSet “REPLICA_SET_INSTANCE_NAME” Example mongod –port 27017 –dbpath “D:set upmongodbdata” –replSet rs0 It will start a mongod instance with the name rs0, on port 27017. Now start the command prompt and connect to this mongod instance. In Mongo client, issue the command rs.initiate() to initiate a new replica set. To check the replica set configuration, issue the command rs.conf(). To check the status of replica set issue the command rs.status(). Add Members to Replica Set To add members to replica set, start mongod instances on multiple machines. Now start a mongo client and issue a command rs.add(). Syntax The basic syntax of rs.add() command is as follows − >rs.add(HOST_NAME:PORT) Example Suppose your mongod instance name is mongod1.net and it is running on port 27017. To add this instance to replica set, issue the command rs.add() in Mongo client. >rs.add(“mongod1.net:27017″) > You can add mongod instance to replica set only when you are connected to primary node. To check whether you are connected to primary or not, issue the command db.isMaster() in mongo client. Print Page Previous Next Advertisements ”;

MongoDB – Projection

MongoDB – Projection ”; Previous Next In MongoDB, projection means selecting only the necessary data rather than selecting whole of the data of a document. If a document has 5 fields and you need to show only 3, then select only 3 fields from them. The find() Method MongoDB”s find() method, explained in MongoDB Query Document accepts second optional parameter that is list of fields that you want to retrieve. In MongoDB, when you execute find() method, then it displays all fields of a document. To limit this, you need to set a list of fields with value 1 or 0. 1 is used to show the field while 0 is used to hide the fields. Syntax The basic syntax of find() method with projection is as follows − >db.COLLECTION_NAME.find({},{KEY:1}) Example Consider the collection mycol has the following data − {_id : ObjectId(“507f191e810c19729de860e1”), title: “MongoDB Overview”}, {_id : ObjectId(“507f191e810c19729de860e2”), title: “NoSQL Overview”}, {_id : ObjectId(“507f191e810c19729de860e3”), title: “Tutorials Point Overview”} Following example will display the title of the document while querying the document. >db.mycol.find({},{“title”:1,_id:0}) {“title”:”MongoDB Overview”} {“title”:”NoSQL Overview”} {“title”:”Tutorials Point Overview”} > Please note _id field is always displayed while executing find() method, if you don”t want this field, then you need to set it as 0. Print Page Previous Next Advertisements ”;

MongoDB – Limiting Records

MongoDB – Limit Records ”; Previous Next In this chapter, we will learn how to limit records using MongoDB. The Limit() Method To limit the records in MongoDB, you need to use limit() method. The method accepts one number type argument, which is the number of documents that you want to be displayed. Syntax The basic syntax of limit() method is as follows − >db.COLLECTION_NAME.find().limit(NUMBER) Example Consider the collection myycol has the following data. {_id : ObjectId(“507f191e810c19729de860e1”), title: “MongoDB Overview”}, {_id : ObjectId(“507f191e810c19729de860e2”), title: “NoSQL Overview”}, {_id : ObjectId(“507f191e810c19729de860e3”), title: “Tutorials Point Overview”} Following example will display only two documents while querying the document. >db.mycol.find({},{“title”:1,_id:0}).limit(2) {“title”:”MongoDB Overview”} {“title”:”NoSQL Overview”} > If you don”t specify the number argument in limit() method then it will display all documents from the collection. MongoDB Skip() Method Apart from limit() method, there is one more method skip() which also accepts number type argument and is used to skip the number of documents. Syntax The basic syntax of skip() method is as follows − >db.COLLECTION_NAME.find().limit(NUMBER).skip(NUMBER) Example Following example will display only the second document. >db.mycol.find({},{“title”:1,_id:0}).limit(1).skip(1) {“title”:”NoSQL Overview”} > Please note, the default value in skip() method is 0. Print Page Previous Next Advertisements ”;

MongoDB – Update Document

MongoDB – Update Document ”; Previous Next MongoDB”s update() and save() methods are used to update document into a collection. The update() method updates the values in the existing document while the save() method replaces the existing document with the document passed in save() method. MongoDB Update() Method The update() method updates the values in the existing document. Syntax The basic syntax of update() method is as follows − >db.COLLECTION_NAME.update(SELECTION_CRITERIA, UPDATED_DATA) Example Consider the mycol collection has the following data. { “_id” : ObjectId(5983548781331adf45ec5), “title”:”MongoDB Overview”} { “_id” : ObjectId(5983548781331adf45ec6), “title”:”NoSQL Overview”} { “_id” : ObjectId(5983548781331adf45ec7), “title”:”Tutorials Point Overview”} Following example will set the new title ”New MongoDB Tutorial” of the documents whose title is ”MongoDB Overview”. >db.mycol.update({”title”:”MongoDB Overview”},{$set:{”title”:”New MongoDB Tutorial”}}) WriteResult({ “nMatched” : 1, “nUpserted” : 0, “nModified” : 1 }) >db.mycol.find() { “_id” : ObjectId(5983548781331adf45ec5), “title”:”New MongoDB Tutorial”} { “_id” : ObjectId(5983548781331adf45ec6), “title”:”NoSQL Overview”} { “_id” : ObjectId(5983548781331adf45ec7), “title”:”Tutorials Point Overview”} > By default, MongoDB will update only a single document. To update multiple documents, you need to set a parameter ”multi” to true. >db.mycol.update({”title”:”MongoDB Overview”}, {$set:{”title”:”New MongoDB Tutorial”}},{multi:true}) MongoDB Save() Method The save() method replaces the existing document with the new document passed in the save() method. Syntax The basic syntax of MongoDB save() method is shown below − >db.COLLECTION_NAME.save({_id:ObjectId(),NEW_DATA}) Example Following example will replace the document with the _id ”5983548781331adf45ec5”. >db.mycol.save( { “_id” : ObjectId(“507f191e810c19729de860ea”), “title”:”Tutorials Point New Topic”, “by”:”Tutorials Point” } ) WriteResult({ “nMatched” : 0, “nUpserted” : 1, “nModified” : 0, “_id” : ObjectId(“507f191e810c19729de860ea”) }) >db.mycol.find() { “_id” : ObjectId(“507f191e810c19729de860e6”), “title”:”Tutorials Point New Topic”, “by”:”Tutorials Point”} { “_id” : ObjectId(“507f191e810c19729de860e6”), “title”:”NoSQL Overview”} { “_id” : ObjectId(“507f191e810c19729de860e6”), “title”:”Tutorials Point Overview”} > MongoDB findOneAndUpdate() method The findOneAndUpdate() method updates the values in the existing document. Syntax The basic syntax of findOneAndUpdate() method is as follows − >db.COLLECTION_NAME.findOneAndUpdate(SELECTIOIN_CRITERIA, UPDATED_DATA) Example Assume we have created a collection named empDetails and inserted three documents in it as shown below − > db.empDetails.insertMany( [ { First_Name: “Radhika”, Last_Name: “Sharma”, Age: “26”, e_mail: “[email protected]”, phone: “9000012345” }, { First_Name: “Rachel”, Last_Name: “Christopher”, Age: “27”, e_mail: “[email protected]”, phone: “9000054321” }, { First_Name: “Fathima”, Last_Name: “Sheik”, Age: “24”, e_mail: “[email protected]”, phone: “9000054321” } ] ) Following example updates the age and email values of the document with name ”Radhika”. > db.empDetails.findOneAndUpdate( {First_Name: ”Radhika”}, { $set: { Age: ”30”,e_mail: ”[email protected]”}} ) { “_id” : ObjectId(“5dd6636870fb13eec3963bf5”), “First_Name” : “Radhika”, “Last_Name” : “Sharma”, “Age” : “30”, “e_mail” : “[email protected]”, “phone” : “9000012345” } MongoDB updateOne() method This methods updates a single document which matches the given filter. Syntax The basic syntax of updateOne() method is as follows − >db.COLLECTION_NAME.updateOne(<filter>, <update>) Example > db.empDetails.updateOne( {First_Name: ”Radhika”}, { $set: { Age: ”30”,e_mail: ”[email protected]”}} ) { “acknowledged” : true, “matchedCount” : 1, “modifiedCount” : 0 } > MongoDB updateMany() method The updateMany() method updates all the documents that matches the given filter. Syntax The basic syntax of updateMany() method is as follows − >db.COLLECTION_NAME.update(<filter>, <update>) Example > db.empDetails.updateMany( {Age:{ $gt: “25” }}, { $set: { Age: ”00”}} ) { “acknowledged” : true, “matchedCount” : 2, “modifiedCount” : 2 } You can see the updated values if you retrieve the contents of the document using the find method as shown below − > db.empDetails.find() { “_id” : ObjectId(“5dd6636870fb13eec3963bf5”), “First_Name” : “Radhika”, “Last_Name” : “Sharma”, “Age” : “00”, “e_mail” : “[email protected]”, “phone” : “9000012345” } { “_id” : ObjectId(“5dd6636870fb13eec3963bf6”), “First_Name” : “Rachel”, “Last_Name” : “Christopher”, “Age” : “00”, “e_mail” : “[email protected]”, “phone” : “9000054321” } { “_id” : ObjectId(“5dd6636870fb13eec3963bf7”), “First_Name” : “Fathima”, “Last_Name” : “Sheik”, “Age” : “24”, “e_mail” : “[email protected]”, “phone” : “9000054321” } > Print Page Previous Next Advertisements ”;

MongoDB – Aggregation

MongoDB – Aggregation ”; Previous Next Aggregations operations process data records and return computed results. Aggregation operations group values from multiple documents together, and can perform a variety of operations on the grouped data to return a single result. In SQL count(*) and with group by is an equivalent of MongoDB aggregation. The aggregate() Method For the aggregation in MongoDB, you should use aggregate() method. Syntax Basic syntax of aggregate() method is as follows − >db.COLLECTION_NAME.aggregate(AGGREGATE_OPERATION) Example In the collection you have the following data − { _id: ObjectId(7df78ad8902c) title: ”MongoDB Overview”, description: ”MongoDB is no sql database”, by_user: ”tutorials point”, url: ”http://www.tutorialspoint.com”, tags: [”mongodb”, ”database”, ”NoSQL”], likes: 100 }, { _id: ObjectId(7df78ad8902d) title: ”NoSQL Overview”, description: ”No sql database is very fast”, by_user: ”tutorials point”, url: ”http://www.tutorialspoint.com”, tags: [”mongodb”, ”database”, ”NoSQL”], likes: 10 }, { _id: ObjectId(7df78ad8902e) title: ”Neo4j Overview”, description: ”Neo4j is no sql database”, by_user: ”Neo4j”, url: ”http://www.neo4j.com”, tags: [”neo4j”, ”database”, ”NoSQL”], likes: 750 }, Now from the above collection, if you want to display a list stating how many tutorials are written by each user, then you will use the following aggregate() method − > db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$sum : 1}}}]) { “_id” : “tutorials point”, “num_tutorial” : 2 } { “_id” : “Neo4j”, “num_tutorial” : 1 } > Sql equivalent query for the above use case will be select by_user, count(*) from mycol group by by_user. In the above example, we have grouped documents by field by_user and on each occurrence of by user previous value of sum is incremented. Following is a list of available aggregation expressions. Expression Description Example $sum Sums up the defined value from all documents in the collection. db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$sum : “$likes”}}}]) $avg Calculates the average of all given values from all documents in the collection. db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$avg : “$likes”}}}]) $min Gets the minimum of the corresponding values from all documents in the collection. db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$min : “$likes”}}}]) $max Gets the maximum of the corresponding values from all documents in the collection. db.mycol.aggregate([{$group : {_id : “$by_user”, num_tutorial : {$max : “$likes”}}}]) $push Inserts the value to an array in the resulting document. db.mycol.aggregate([{$group : {_id : “$by_user”, url : {$push: “$url”}}}]) $addToSet Inserts the value to an array in the resulting document but does not create duplicates. db.mycol.aggregate([{$group : {_id : “$by_user”, url : {$addToSet : “$url”}}}]) $first Gets the first document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage. db.mycol.aggregate([{$group : {_id : “$by_user”, first_url : {$first : “$url”}}}]) $last Gets the last document from the source documents according to the grouping. Typically this makes only sense together with some previously applied “$sort”-stage. db.mycol.aggregate([{$group : {_id : “$by_user”, last_url : {$last : “$url”}}}]) Pipeline Concept In UNIX command, shell pipeline means the possibility to execute an operation on some input and use the output as the input for the next command and so on. MongoDB also supports same concept in aggregation framework. There is a set of possible stages and each of those is taken as a set of documents as an input and produces a resulting set of documents (or the final resulting JSON document at the end of the pipeline). This can then in turn be used for the next stage and so on. Following are the possible stages in aggregation framework − $project − Used to select some specific fields from a collection. $match − This is a filtering operation and thus this can reduce the amount of documents that are given as input to the next stage. $group − This does the actual aggregation as discussed above. $sort − Sorts the documents. $skip − With this, it is possible to skip forward in the list of documents for a given amount of documents. $limit − This limits the amount of documents to look at, by the given number starting from the current positions. $unwind − This is used to unwind document that are using arrays. When using an array, the data is kind of pre-joined and this operation will be undone with this to have individual documents again. Thus with this stage we will increase the amount of documents for the next stage. Print Page Previous Next Advertisements ”;

MongoDB – Sorting Records

MongoDB – Sort Records ”; Previous Next In this chapter, we will learn how to sort records in MongoDB. The sort() Method To sort documents in MongoDB, you need to use sort() method. The method accepts a document containing a list of fields along with their sorting order. To specify sorting order 1 and -1 are used. 1 is used for ascending order while -1 is used for descending order. Syntax The basic syntax of sort() method is as follows − >db.COLLECTION_NAME.find().sort({KEY:1}) Example Consider the collection myycol has the following data. {_id : ObjectId(“507f191e810c19729de860e1”), title: “MongoDB Overview”} {_id : ObjectId(“507f191e810c19729de860e2”), title: “NoSQL Overview”} {_id : ObjectId(“507f191e810c19729de860e3”), title: “Tutorials Point Overview”} Following example will display the documents sorted by title in the descending order. >db.mycol.find({},{“title”:1,_id:0}).sort({“title”:-1}) {“title”:”Tutorials Point Overview”} {“title”:”NoSQL Overview”} {“title”:”MongoDB Overview”} > Please note, if you don”t specify the sorting preference, then sort() method will display the documents in ascending order. Print Page Previous Next Advertisements ”;

MongoDB – Relationships

MongoDB – Relationships ”; Previous Next Relationships in MongoDB represent how various documents are logically related to each other. Relationships can be modeled via Embedded and Referenced approaches. Such relationships can be either 1:1, 1:N, N:1 or N:N. Let us consider the case of storing addresses for users. So, one user can have multiple addresses making this a 1:N relationship. Following is the sample document structure of user document − { “_id”:ObjectId(“52ffc33cd85242f436000001”), “name”: “Tom Hanks”, “contact”: “987654321”, “dob”: “01-01-1991” } Following is the sample document structure of address document − { “_id”:ObjectId(“52ffc4a5d85242602e000000”), “building”: “22 A, Indiana Apt”, “pincode”: 123456, “city”: “Los Angeles”, “state”: “California” } Modeling Embedded Relationships In the embedded approach, we will embed the address document inside the user document. > db.users.insert({ { “_id”:ObjectId(“52ffc33cd85242f436000001”), “contact”: “987654321”, “dob”: “01-01-1991”, “name”: “Tom Benzamin”, “address”: [ { “building”: “22 A, Indiana Apt”, “pincode”: 123456, “city”: “Los Angeles”, “state”: “California” }, { “building”: “170 A, Acropolis Apt”, “pincode”: 456789, “city”: “Chicago”, “state”: “Illinois” } ] } }) This approach maintains all the related data in a single document, which makes it easy to retrieve and maintain. The whole document can be retrieved in a single query such as − >db.users.findOne({“name”:”Tom Benzamin”},{“address”:1}) Note that in the above query, db and users are the database and collection respectively. The drawback is that if the embedded document keeps on growing too much in size, it can impact the read/write performance. Modeling Referenced Relationships This is the approach of designing normalized relationship. In this approach, both the user and address documents will be maintained separately but the user document will contain a field that will reference the address document”s id field. { “_id”:ObjectId(“52ffc33cd85242f436000001”), “contact”: “987654321”, “dob”: “01-01-1991”, “name”: “Tom Benzamin”, “address_ids”: [ ObjectId(“52ffc4a5d85242602e000000”), ObjectId(“52ffc4a5d85242602e000001”) ] } As shown above, the user document contains the array field address_ids which contains ObjectIds of corresponding addresses. Using these ObjectIds, we can query the address documents and get address details from there. With this approach, we will need two queries: first to fetch the address_ids fields from user document and second to fetch these addresses from address collection. >var result = db.users.findOne({“name”:”Tom Benzamin”},{“address_ids”:1}) >var addresses = db.address.find({“_id”:{“$in”:result[“address_ids”]}}) Print Page Previous Next Advertisements ”;