Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

MongoDB Query Documents

MongoDB Query Documents

MongoDB query documents use the find() and findOne() methods.

The find() method displays all documents in an unstructured way.

Syntax

The syntax format for MongoDB data queries is as follows:

db.collection.find(query, projection)

Find all documents:

Example

db.

myCollection

.

find

(

)

;

Find documents by condition:

Example

db.

myCollection

.

find

(

{

age

:

{

$gt

:

25

}

}

)

;

Find documents by condition and return only specified fields:

Example

db.

myCollection

.

find

(

   

{

age

:

{

$gt

:

25

}

}

,

   

{

name

:

1

,

age

:

1

,

_id

:

0

}

)

;

If you need to read data in a human-readable way, you can use the pretty() method. The syntax format is as follows:



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

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

Example

db.

col

.

find

(

)

.

pretty

(

)

{

       

"_id"

:

ObjectId

(

"56063f17ade2f21f36b03133"

)

,

       

"title"

:

"MongoDB Tutorial"

,

       

"description"

:

"MongoDB is a Nosql database"

,

       

"by"

:

"Runoob Tutorial"

,

       

"url"

:

"http://www.runoob.com"

,

       

"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)

Find a single document:



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

Find a single document and return only specified fields:



db.myCollection.findOne(

    { name: "Alice" },

    { name: 1, age: 1, _id: 0 }

);


Advanced query methods

1. Using comparison operators

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

Find documents where age is greater than 25:



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

2. Using logical operators

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

Find documents where age is greater than 25 and city is "New York":

Example

db.

myCollection

.

find

(

{

    $and

:

[

       

{

age

:

{

$gt

:

25

}

}

,

       

{

city

:

"New York"

}

   

]

}

)

;

3. Using regular expressions

You can use regular expressions for pattern matching queries.

Find documents where the name starts with "A":



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

4. Projection

Projection is used to control which fields are returned in query results. Two methods can be used: inclusion fields and exclusion fields.

Return only the name and age fields:

Example

db.

myCollection

.

find

(

   

{

age

:

{

$gt

:

25

}

}

,

   

{

name

:

1

,

age

:

1

,

_id

:

0

}

)

;

5. Sorting

You can sort the query results.

Sort by age in descending order:



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

6. Limit and skip

You can limit the query results and skip a specified number of documents.

Return the first 10 documents:



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

Skip the first 5 documents and return the next 10 documents:



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

Example

Find documents where age is greater than 25 and city is "New York", return only the name and age fields, sort by age in descending order, and return the first 10 documents.

Example

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 Statement Comparison

If you are familiar with conventional SQL data, the following table can help you better understand MongoDB conditional statement queries:

Operation Format Example Similar statements in RDBMS
Equal {:} db.col.find({"by":"Runoob Tutorial"}).pretty() where by = 'Runoob Tutorial'
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 equal {:{$ne:}} db.col.find({"likes":{$ne:50}}).pretty() where likes != 50

MongoDB AND Conditions

MongoDB's find() method can take multiple keys, each separated by a comma, which is the AND condition in conventional SQL.

The syntax format is as follows:



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

Example

The following example uses by and title key to query Runoob Tutorial Medium MongoDB Tutorial data



> db.col.find({"by":"Runoob Tutorial", "title":"MongoDB 教程"}).pretty()

{

        "_id" : ObjectId("56063f17ade2f21f36b03133"),

        "title" : "MongoDB 教程",

        "description" : "MongoDB 是一个 Nosql 数据库",

        "by" : "Runoob Tutorial",

        "url" : "http://www.runoob.com",

        "tags" : [

                "mongodb",

                "database",

                "NoSQL"

        ],

        "likes" : 100

}

The above example is similar to the WHERE statement:WHERE by='Runoob Tutorial' AND title='MongoDB Tutorial'


MongoDB OR Conditions

MongoDB OR conditional statements use the keyword $or, the syntax format is as follows:



>db.col.find(

   {

      $or: [

         {key1: value1}, {key2:value2}

      ]

   }

).pretty()

Example

In the following example, we demonstrate querying the key by with value Runoob Tutorial or the key title with value MongoDB Tutorial documents.



>db.col.find({$or:[{"by":"Runoob Tutorial"},{"title": "MongoDB 教程"}]}).pretty()

{

        "_id" : ObjectId("56063f17ade2f21f36b03133"),

        "title" : "MongoDB 教程",

        "description" : "MongoDB 是一个 Nosql 数据库",

        "by" : "Runoob Tutorial",

        "url" : "http://www.runoob.com",

        "tags" : [

                "mongodb",

                "database",

                "NoSQL"

        ],

        "likes" : 100

}

>


Combined use of AND and OR

The following example demonstrates the combined use of AND and OR, similar to the conventional SQL statement: 'where likes>50 AND (by = 'Runoob Tutorial' OR title = 'MongoDB Tutorial')'



>db.col.find({"likes": {$gt:50}, $or: [{"by": "Runoob Tutorial"},{"title": "MongoDB 教程"}]}).pretty()

{

        "_id" : ObjectId("56063f17ade2f21f36b03133"),

        "title" : "MongoDB 教程",

        "description" : "MongoDB 是一个 Nosql 数据库",

        "by" : "Runoob Tutorial",

        "url" : "http://www.runoob.com",

        "tags" : [

                "mongodb",

                "database",

                "NoSQL"

        ],

        "likes" : 100

}