English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this chapter, we will learn how to query documents from MongoDB collections.
To query data from a MongoDB collection, you need to use MongoDB'sfind()method.
find()The basic syntax of the method is as follows-
> db.COLLECTION_NAME.find()
find() The method will display all documents in a non-structured manner.
Assuming we have created a collection named mycol-
> use sampleDB switched to db sampleDB > db.createCollection("mycol") { "ok": :}} 1 } >
and use the insert() method to insert into it3documents, as shown below-
> db.mycol.insert([ { title: "MongoDB Overview", description: "MongoDB is not a SQL database", by: "Basic Tutorial", url: "http://www.oldtoolbag.com", tags: ["mongodb", "database", "NoSQL"], likes: 100 }, { title: "NoSQL Database", description: "NoSQL databases do not have tables", by: "Basic Tutorial", url: "http://www.oldtoolbag.com", tags: ["mongodb", "database", "NoSQL"], likes: 20, comments: [ { user: "user1", message: "My first comment", dateCreated: new Date(",2013,11,10,2,35), like: 0 } ] } ])
The following methods retrieve all documents in the collection-
> db.mycol.find() { "_id": ObjectId("5dd4e2cc0821d3b44607534c"), "title": "MongoDB Overview", "description": "MongoDB is not a SQL database", "by": "Basic Tutorial", "url": "http://www.oldtoolbag.com", "tags": [ "mongodb", "database", "NoSQL" ], "likes": 100 } { "_id": ObjectId("5dd4e2cc0821d3b44607534d"), "title": "NoSQL Database", "description": "NoSQL databases do not have tables", "by": "Basic Tutorial", "url": "http://www.oldtoolbag.com", "tags": [ "mongodb", "database", "NoSQL" ], "likes": 20, "comments": [ { "user": "user1", "message": "My first comment", "dateCreated": ISODate("2013-12-09T21:05:00Z"), "like": 0 } ]} >
To display the results in a formatted way, you can use the pretty() method.
> db.COLLECTION_NAME.find().pretty()
The following example retrieves all documents from a collection named mycol and displays them in a readable format.
> db.mycol.find().pretty() { "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), "title": "MongoDB Overview", "description": "MongoDB is not a SQL database", "by": "basic tutorial", "url" : "http://www.oldtoolbag.com", "tags": [ "mongodb", "database", "NoSQL" ], "likes": 100 } { "_id" : ObjectId("5dd4e2cc0821d3b44607534d"), "title": "NoSQL Database", "description" : "NoSQL databases do not have tables" "by": "basic tutorial", "url" : "http://www.oldtoolbag.com", "tags": [ "mongodb", "database", "NoSQL" ], "likes": 20, "comments" : [ { "user" : "user1", "message" : "My first comment", "dateCreated" : ISODate("2013-12-09T21:05:00Z"), "like" : 0 } ] }
In addition to the find() method, there is also afindOne()The method returns only one document.
>db.COLLECTIONNAME.findOne()
The following example retrieves the document with the title MongoDB Overview.
> db.mycol.findOne({title: "MongoDB Overview"}) { "_id" : ObjectId("5dd6542170fb13eec3963bf0"), "title": "MongoDB Overview", "description": "MongoDB is not a SQL database", "by": "basic tutorial", "url" : "http://www.oldtoolbag.com", "tags": [ "mongodb", "database", "NoSQL" ], "likes": 100 }
To query documents based on certain conditions, you can use the following operations.
Operation | Format | Example | Similar statements in RDBMS |
---|---|---|---|
Equal to | {<key>:<value>} | db.col.find({"by":"Basic Tutorial"}).pretty() | where by = 'Basic Tutorial' |
Less than | {<key>:{$lt:<value>}} | db.col.find({"likes":{$lt:50}).pretty() | where likes < 50 |
Less than or equal to | {<key>:{$lte:<value>}} | db.col.find({"likes":{$lte:50}).pretty() | where likes <= 50 |
Greater than | {<key>:{$gt:<value>}} | db.col.find({"likes":{$gt:50}).pretty() | where likes > 50 |
Greater than or equal to | {<key>:{$gte:<value>}} | db.col.find({"likes":{$gte:50}).pretty() | where likes >= 50 |
Not equal to | {<key>:{$ne:<value>}} | db.col.find({"likes":{$ne:50}).pretty() | where likes != 50 |
The value is in the array | {<key>:{$in:[<value1>, <value2>,……<valueN>] | db.mycol.find({"name":{$in:["Raj", "Ram", "Raghu"]}}).pretty() | where name matches any of the values in :["Raj", "Ram", "Raghu"] |
value is not in the array | {<key>:{$nin:<value>}} | db.mycol.find({"name":{$nin:["Ramu", "Raghav"]}}).pretty() | name value is not in the array :["Ramu", "Raghav"] or does not exist at all |
To query documents based on the "AND" condition, you need to use the $and keyword. The basic syntax of AND is as follows-
>db.mycol.find({ $and: [ {<key1>:<value1>}, { <key2>:<value2>}]})
The following example will display all tutorials written by "basic tutorial" and with the title "MongoDB Overview".
> db.mycol.find({$and:[{"by":"basic tutorial"},{"title": "MongoDB Overview"}]}).pretty() { "_id" : ObjectId("5dd4e2cc0821d3b44607534c"), "title": "MongoDB Overview", "description": "MongoDB is not a SQL database", "by": "basic tutorial", "url": "https://www.oldtoolbag.com", "tags": [ "mongodb", "database", "NoSQL" ], "likes": 100 } >
For the example given above, the equivalent where clause will be' where by = 'basic tutorial' AND title = 'MongoDB Overview' '. You can pass any number of key-value pairs in the find clause.
To query documents based on the "OR" condition, you need to use$orkeyword. The following isORBasic Syntax:
>db.mycol.find( { $or: [ {key1: value1}, {key2:value2} ] } ).pretty()
The following example will display all tutorials written by "tutorials point" or with the title "MongoDB Overview".
>db.mycol.find({$or:[{"by":"tutorials point"},{"title": "MongoDB Overview"}]}).pretty() { "_id": ObjectId(7df78ad8902c), "title": "MongoDB Overview", "description": "MongoDB is not a SQL database", "by": "Basic Tutorial", "url": "http://www.oldtoolbag.com", "tags": ["mongodb", "database", "NoSQL"], "likes": "100" } >
The following example will display documents where likes are greater than10documents with likes greater than and the title is 'MongoDB Overview' or by is 'Basic Tutorial'. Equivalent to SQL WHERE clause 'where likes>10 AND (by = '基础教程' OR title = 'MongoDB概述')
>db.mycol.find({"likes": {$gt:10}, $or: [{"by": "tutorials point"}, {"title": "MongoDB Overview"}).pretty() { "_id": ObjectId(7df78ad8902c), "title": "MongoDB Overview", "description": "MongoDB is not a SQL database", "by": "Basic Tutorial", "url": "http://www.oldtoolbag.com", "tags": ["mongodb", "database", "NoSQL"], "likes": "100" } >
To query documents using NOR conditions, the $nor keyword must be used. Below isNORBasic Syntax:
> db.COLLECTION_NAME.find( { $nor: [ {key1: value1}, {key2:value2} ] } )
Assuming we are in the collection empDetails were inserted into3documents, 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" } ] )
The following example retrieves documents where the name is not "Radhika" and the name is also 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" : "[email protected]", "phone" : "9000054321" }
To query documents based on NOT condition, you need to use the $not keyword, as follows}}NOTBasic Syntax:
> db.COLLECTION_NAME.find( { $NOT: [ {key1: value1}, {key2:value2} ] } ).pretty()
The following example will retrieve documents whose age is not more than25years old documents
> db.empDetails.find({ "Age": { $not: { $gt: "25"} } }" { "_id" : ObjectId("5dd6636870fb13eec3963bf7") "First_Name" : "Fathima", "Last_Name" : "Sheik", "Age" : "24", "e_mail" : "[email protected]", "phone" : "9000054321" }