MongoDB Query Document

In this post, we will learn how to query a document from the MongoDB collection.
The examples in this post use the posts collection. To populate the posts collection, run the following:
db.posts.insertMany([
   {
      title: 'MongoDB Overview', 
      description: 'MongoDB is no sql database',
      by: 'Java Guides',
      url: 'https://javaguides.net',
      tags: ['mongodb', 'database', 'NoSQL'],
      likes: 100
   },
 
   {
      title: 'NoSQL Database', 
      description: "NoSQL database doesn't have tables",
       by: 'Java Guides',
      url: 'https://javaguides.net',
      tags: ['mongodb', 'database', 'NoSQL'],
      likes: 20, 
      comments: [ 
         {
            user:'user1',
            message: 'My first comment',
            dateCreated: new Date(2013,11,10,2,35),
            like: 0 
         }
      ]
   }
]);

{
        "acknowledged" : true,
        "insertedIds" : [
                ObjectId("5e18246f7695f4d696a05985"),
                ObjectId("5e18246f7695f4d696a05986")
        ]
}

The find() Method

To query data from MongoDB collection, you need to use MongoDB's find() method.

Syntax

The basic syntax of the find() method is as follows −
> db.COLLECTION_NAME.find()
find() method will display all the documents in a non-structured way.

Select All Documents in a Collection

To select all documents in the collection, pass an empty document as the query filter parameter to the find() method. The query filter parameter determines the select criteria:
db.posts.find( {} )
This operation corresponds to the following SQL statement:
SELECT * FROM posts

Example

> db.posts.find( {} );
{ "_id" : ObjectId("5e1840697695f4d696a05987"), "title" : "MongoDB Overview", "description" : "MongoDB is no sql database", "by" : "Java Guides", "url" : "https://javaguides.net", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100 }
{ "_id" : ObjectId("5e1840697695f4d696a05988"), "title" : "NoSQL Database", "description" : "NoSQL database doesn't have tables", "by" : "Java Guides", "url" : "https://javaguides.net", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 20, "comments" : [ { "user" : "user1", "message" : "My first comment", "dateCreated" : ISODate("2013-12-10T09:35:00Z"), "like" : 0 } ] }

The pretty() Method

To display the results in a formatted way, you can use the pretty() method.

Syntax

> db.posts.find().pretty()

Example

> db.posts.find().pretty()
{
        "_id" : ObjectId("5e1840697695f4d696a05987"),
        "title" : "MongoDB Overview",
        "description" : "MongoDB is no sql database",
        "by" : "Java Guides",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 100
}
{
        "_id" : ObjectId("5e1840697695f4d696a05988"),
        "title" : "NoSQL Database",
        "description" : "NoSQL database doesn't have tables",
        "by" : "Java Guides",
        "url" : "https://javaguides.net",
        "tags" : [
                "mongodb",
                "database",
                "NoSQL"
        ],
        "likes" : 20,
        "comments" : [
                {
                        "user" : "user1",
                        "message" : "My first comment",
                        "dateCreated" : ISODate("2013-12-10T09:35:00Z"),
                        "like" : 0
                }
        ]
}

AND in MongoDB

Syntax

In the find() method, if you pass multiple keys by separating them by ',' then MongoDB treats it as AND condition. 
Following is the basic syntax of AND −
> db.mycol.find(
   {
      $and: [
         {key1: value1}, {key2:value2}
      ]
   }
).pretty()

Example

The following example will show all the tutorials written by 'Java Guides' and whose title is 'MongoDB Overview'.
>db.mycol.find({$and:[{"by":"Java Guides"},{"title": "MongoDB Overview"}]}).pretty() {
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "Java Guides",
   "url": "https://javaguides.net",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}
For the above-given example, the equivalent where clause will be ' where by = 'Java Guides' 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.posts.find(
   {
      $or: [
         {key1: value1}, {key2:value2}
      ]
   }
).pretty()

Example

The following example will show all the tutorials written by 'Java Guides' or whose title is 'MongoDB Overview'.
> db.posts.find({$or:[{"by":"Java Guides"},{"title": "MongoDB Overview"}]}).pretty()
{
   "_id": ObjectId(7df78ad8902c),
   "title": "MongoDB Overview", 
   "description": "MongoDB is no sql database",
   "by": "Java Guides",
   "url": "https://javaguides.net",
   "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 'Java Guides'. The equivalent SQL where clause is 'where likes>10 AND (by = 'Java Guides' 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": "Java Guides",
   "url": "https://javaguides.net",
   "tags": ["mongodb", "database", "NoSQL"],
   "likes": "100"
}

Comments