Welcome back to the MongoDB article series - Part 3. In the previous article, we discussed the different processes to insert, update, and delete the data in MongoDB. Now, in this article, we will discuss the basic search command of a MongoDB Database. Also, in this article, we will discuss how to use custom search conditions in MongoDB. If you want to read the previous articles of these series, then follow the links.
- Introduction to MongoDB - Part One
- Insert, Update and Delete Document in MongoDB - Part Two
In the previous article, we already discussed how to create the database and also, perform insert, update and delete operations in MongoDB. Now, in this article, we will discuss querying the data in the MongoDB. We can perform any type of adhoc queries on the database to find a particular group of data. Also, we can use the range operator for the data query logic. In MongoDB, each query command returns a cursor which basically returns the batch of documents as we provide the conditions of search.
Find()
Find()
The most common and popular command for finding the data in MongoDB is the find() method. This command always returns a subset collection of the documents. In this query command, it will return the documents which match with first arguments provided in the query criteria. If no condition or criteria are specified (i.e. empty string in the condition) it means it will match all documents of the collections and return it.
db.Employee.find()
db.Employee.find()
Now, if we add the conditions as key/value pairs in the condition, then MongoDB restricts our search. It simply works in a straightforward logic as per the data types like string matches string, number matches number, and so on. Now, if the Employee collections we want to find are all documents of an employee whose salary is 16000, so in that case, we need to use condition within the find().
db.Employee.find({“Salary”:16000})
db.Employee.find({“Salary”:16000})
Similarly, we can find the employee list for the Accounts Departments as below,
Also, remember that MongoDB is basically case sensitive. That’s why in the yellow marked command it does not return any value since the provided value of the department name does not match exactly with the original data in the collections. Also, we can provide the multiple conditions together for searching any documents within the collections as a key/value pairs. By default, all the conditions are merged with each other with AND logical operators. This means to return all the data, all the conditions need to be matched in the collections. So, we want to find the document list of the Products collection where manufacturer name is apple and price is above 550.
db.Products.find({"manufacturer":"Apple","price":499})
Query Conditions
Also, remember that MongoDB is basically case sensitive. That’s why in the yellow marked command it does not return any value since the provided value of the department name does not match exactly with the original data in the collections. Also, we can provide the multiple conditions together for searching any documents within the collections as a key/value pairs. By default, all the conditions are merged with each other with AND logical operators. This means to return all the data, all the conditions need to be matched in the collections. So, we want to find the document list of the Products collection where manufacturer name is apple and price is above 550.
db.Products.find({"manufacturer":"Apple","price":499})
Query Conditions
In the real world, query conditions can contain more complex search conditions except exact matching. So actually the find() method can match more complex conditions like range, or – clause and other like less than, greater than etc. The below tables represents the list of such complex query operators which can be used in find method,
Operator | Descriptions | Example |
$lt | This operator means less than. It normally represents the < sign. It is applicable only for number types. | db.Products.find({“price”:{“$lt”:750}})This command returns document list whose price is below 750 |
$gt | This operator means greater than. It normally represents the > sign. It is application only for number types. | db.Products.find({“price”:{“$gt”:750}})This command returns document list whose price is above 750 |
$lte | This operator means less than and equal to. It normally represents the <= sign. It is applicable only for number types. | db.Products.find({“price”:{“$lte”:750}})This command returns document list whose price is below or equal to 750 |
$gte | This operator means greater than and equal to. It normally represents the >= sign. It is applicable only for number types. | db.Products.find({“price”:{“$gte”:750}})This command returns document list whose price is equal to and above 750 |
$ne | This operator means not equal to. It is the just opposite of exact search conditions. It is applicable only for number types. | db.Products.find({“manufacturer”:{“$ne”:”Apple”}})This command returns the document list whose manufacturer are not Apple. |
Range | Basically, there is no special operator for the range type query. We need to use above five operators for implements that like the example. It is applicable in any type of data. | db.Products.find({“price”:{“$gte”:500, “$lte”:1200}})This command returns document list whose price range is between 500 and 1200. |
$in | This operator is basically used for implementing OR logical operator in the criteria expression. It is used to fetch any documents for a list of values against a single key. It is not applicable to multiple keys. It can be used against any type of data. | db.Products.find({“manufacturer”:{“$in”:[”Apple”,”Samsung”}})This command returns the document list whose manufacturer are either Apple or Samsung. |
$nin | This operator is just the opposite of the $in operator. | db.Products.find({“manufacturer”:{“$nin”:[”Apple”,”Samsung”}})This command returns the document list whose manufacturer are not Apple or Samsung. |
$or | This operator is basically used for implementing OR logical operator in the criteria expression. It is used to fetch any documents for a list of values against multiple key values. It is not applicable to multiple keys. It can be used against any type of data. | db.Products.find({“$or”:[{“manufacturer“ : “Apple”},{“category” : “Tablets”} ] })This command returns the list of documents whose manufacturer is Apple and Category is Tablets. |
Use Regular Expressions
The other most important and useful way of searching data is by using Regular Expression. Suppose, we want to search all Employee Names whose name starts with Am, then we need to use regular expression like below,
db.Employee.find({“Name”:/Ami/});
In the case of Regular Expression, one thing to remember is that it is case sensitive. Normally, MongoDB uses the Perl Compatible Regular Expression (PCRE) library to match the regular expressions. So it means, any expression which is approved by PCRE is also accepted by the MongoDB Search.db.Employee.find({“Name”:/Ami/});
Find Within ArrayStill now we mainly use querying on the simple one level documents. But sometimes there is a scenario where a document contains an array element as a sub-item or child item within it. In that case, if we need to fetch some data from the documents on the basis of implement conditions on the array elements, then we can use some special criteria commands for fetching the data.
Now, if we want to perform the exact search against the Tags item to then we can use the sample below command,
db.posts.find({"Tags":"Orm"})
Operator | Descriptions | Example |
$all | This operator is used to match array elements if there is more than one element. | db.posts.find({"Tags": {$all : ["Orm", "Van"]}}) This command returns document list which contains both Orm and Van in the Tags Array |
$size | This operator always returns the documents which contain the specified size of the array. | db.posts.find({"Tags": {"$size" :4}}) This command returns the document list which contains 4 items in the Tags Array. |
$slice | This command returns a fixed number of subset elements of the array item. Such as, if we want to return first five commands of the post-collection then we need to use this command. Basically, it is not a criteria command. This command can be operated with any other command as second parameters in the find() method. | db.posts.find({},{"Tags": {"$slice" :2}}) This command returns the all documents with first 2 tag elements. |
If anybody has a query related to this article, then feel free to ask the query.
No comments:
Post a Comment