YouTip LogoYouTip

Mongodb Query

MongoDB Query Documents | Tutorial for Beginners

MongoDB Query Documents | Tutorial for Beginners

MongoDB uses the find() and findOne() methods to query documents.

The find() method displays all documents in a non-structured way.

Syntax

The syntax format for querying data in MongoDB is as follows:

db.collection.find(query, projection)
  • query: The query condition used to find documents. Defaults to {}, which matches all documents.
  • projection (optional): Specifies the fields to include or exclude in the returned result.

Find All Documents:

db.myCollection.find();

Find Documents by Condition:

db.myCollection.find({ age:{ $gt:25}});

Find Documents by Condition and Return Specified Fields:

db.myCollection.find(
    { age:{ $gt:25}},
    { name:1, age:1, _id:0}
    );

If you need to read the data in a readable way, you can use the pretty() method, with the syntax format as follows:

>db.col.find().pretty()

The pretty() method displays all documents in a formatted way.

db.col.find().pretty()
{
"_id": ObjectId("56063f17ade2f21f36b03133"),
"title":"MongoDB Tutorial",
"description":"MongoDB is a NoSQL database",
"by":"Tutorial for Beginners",
"url":"",
"tags":[
"mongodb",
"database",
"NoSQL"
],
"likes":100
}

2、findOne()

The findOne() method is used to find a single document in a collection. If multiple matching documents are found, it returns only the first one.

Syntax:

db.collection.findOne(query, projection)
  • query: The query condition used to find documents. Defaults to {}, which matches all documents.
  • projection (optional): Specifies the fields to include or exclude in the returned result.

Find a Single Document:

db.myCollection.findOne({ name: "Alice" });

Find a Single Document and Return Specified Fields:

db.myCollection.findOne( { name: "Alice" }, { name: 1, age: 1, _id: 0 });

Advanced Query Methods

1、Using Comparison Operators

MongoDB supports various comparison operators such as $gt, $lt, $gte, $lte, $eq, $ne, etc.

Find Documents with Age Greater Than 25:

db.myCollection.find({ age: { $gt: 25 } });

2、Using Logical Operators

MongoDB supports various logical operators such as $and, $or, $not, $nor, etc.

Find Documents with Age Greater Than 25 and City as "New York":

db.myCollection.find({
     $and:[
    { age:{ $gt:25}},
    { city:"New York"}
    ]
    });

3、Using Regular Expressions

Regular expressions can be used for pattern matching queries.

Find Documents with Name Starting with "A":

db.myCollection.find({ name: /^A/ });

4、Projection

Projection is used to control the fields returned in the query results. It can be done using inclusion and exclusion of fields.

Return Only Name and Age Fields:

db.myCollection.find(
    { age:{ $gt:25}},
    { name:1, age:1, _id:0}
    );

5、Sorting

The query results can be sorted.

Sort by Age in Descending Order:

db.myCollection.find().sort({ age: -1 });

6、Limit and Skip

The query results can be limited and skipped by a specified number of documents.

Return First 10 Documents:

db.myCollection.find().limit(10);

Skip First 5 Documents, Return Next 10 Documents:

db.myCollection.find().skip(5).limit(10);

Example

Find Documents with Age Greater Than 25 and City as "New York", Return Only Name and Age Fields, Sort by Age in Descending Order, and Return First 10 Documents.

db.myCollection.find(
    {
     $and:[
    { age:{ $gt:25}},
    { city:"New York"}
    ]
    },
    { name:1, age:1, _id:0}
    ).sort({ age:-1}).limit(10);

MongoDB vs RDBMS WHERE Clause

If you are familiar with regular SQL data, you can better understand MongoDB's conditional statement queries through the following table:

Operation Format Example Similar SQL Statement in RDBMS
Equals {:} db.col.find({"by":"Tutorial for Beginners"}).pretty() where by = 'Tutorial for Beginners'
Less Than {:{$lt:}} db.col.find({"likes":{$lt:50}}).pretty() where likes < 50
Less Than or Equal To {:{$lte:}} db.col.find({"likes":{$lte:50}}).pretty() where likes <= 50
Greater Than {:{$gt:}} db.col.find({"likes":{$gt:50}}).pretty() where likes > 50
Greater Than or Equal To {:{$gte:}} db.col.find({"likes":{$gte:50}}).pretty() where likes >= 50
Not Equals {:{$ne:}} db.col.find({"likes":{$ne:50}}).pretty() where likes != 50

MongoDB AND Condition

MongoDB's find() method can take multiple keys (key), each key separated by a comma, i.e., the AND condition in regular SQL.

Syntax Format:

>db.col.find({key1:value1, key2:value2}).pretty()

Example

The following example queries data for **MongoDB Tutorial** by **Tutorial for Beginners** using the **by** and **title** keys

> db.col.find({"by":"Tutorial for Beginners", "title":"MongoDB Tutorial"}).pretty()
{ "_id" : ObjectId("56063f17ade2f21f36b03133"), "title" : "MongoDB Tutorial", "description" : "MongoDB is a NoSQL database", "by" : "Tutorial for Beginners", "url" : "", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100}

The above example is similar to the WHERE clause: **WHERE by='Tutorial for Beginners' AND title='MongoDB Tutorial'**


MongoDB OR Condition

MongoDB OR condition statements use the keyword **$or**, with the syntax format as follows:

>db.col.find( { $or: [ {key1: value1}, {key2:value2} ] }).pretty()

Example

In the following example, we demonstrate querying documents where the **by** key value is Tutorial for Beginners or the **title** key value is **MongoDB Tutorial**.

>db.col.find({$or:[{"by":"Tutorial for Beginners"},{"title": "MongoDB Tutorial"}]}).pretty()
{ "_id" : ObjectId("56063f17ade2f21f36b03133"), "title" : "MongoDB Tutorial", "description" : "MongoDB is a NoSQL database", "by" : "Tutorial for Beginners", "url" : "", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100}>

Combining AND and OR

The following example demonstrates combining AND and OR, similar to the regular SQL statement: **'where likes>50 AND (by = 'Tutorial for Beginners' OR title = 'MongoDB Tutorial')'**

>db.col.find({"likes": {$gt:50}, $or: [{"by": "Tutorial for Beginners"},{"title": "MongoDB Tutorial"}]}).pretty()
{ "_id" : ObjectId("56063f17ade2f21f36b03133"), "title" : "MongoDB Tutorial", "description" : "MongoDB is a NoSQL database", "by" : "Tutorial for Beginners", "url" : "", "tags" : [ "mongodb", "database", "NoSQL" ], "likes" : 100}
← Mongodb OperatorsMongodb Remove β†’