MongoDB's query operation

Source: Internet
Author: User
Tags mongo shell

1. Preface

In this blog post, we will learn how to query the data in MongoDB. When we store the data in MongoDB, we need to query the data. After all, the query operation in the crud operation is our most frequently used operation in our system. We need to deal with different business needs and construct appropriate query criteria to query the data we want. We need to learn about the syntax and functionality that MONGODB provides to us about queries. Here, we use MongoDB's own MONGO shell (MONGO Shell is a JavaScript client of the environment, support JS syntax ) to learn.

2. Preparation

Before we begin, we need to prepare the data for the experiment:

//start the MONGO shell client$ MONGO//Here we use the test database, without which the database is automatically created>Use test//inserting 6 user data in the Users collection>Db.users.insertMany ([{_id:1, Name:"Sue", Age:19, type:1, Status:P, Favorites: {artist:"Picasso", Food: "Pizza"}, finished: [17, 3], badges: ["Blue", "BLACK"], points: [{points:BONUS:20,}, {points:Bonus:10,}]}, {_id:2, Name:"Bob", Age:42, type:1, Status:A, Favorites: {artist:"Miro", Food: "Meringue"}, finished: [11, 25], badges: ["Green"], points: [{points:BONUS:20,}, {points:Bonus:12,}]}, {_id:3, Name:"Ahn", Age:22, type:2, Status:A, Favorites: {artist:"Cassatt", Food: "Cake"}, finished: [6], badges: ["Blue", "red"], points: [{points:Bayi, Bonus:8}, {points:BONUS:20,}]}, {_id:4, Name:"XI", Age:34, type:2, Status:D, Favorites: {artist:"Chagall", Food: "Chocolate"}, finished: [5, 11], badges: ["Red", "black"], points: [{points:Bonus:15,}, {points:Wuyi, bonus:15}]}, {_id:5, Name:"XYZ", Age:23, type:2, Status:D, Favorites: {artist:"Noguchi", Food: "Nougat"}, finished: [14, 6], badges: ["Orange"], points: [{points:BONUS:20,}]}, {_id:6, Name:"ABC", Age:43, type:1, Status:A, Favorites: {food:"Pizza", Artist: "Picasso"}, finished: [18, 12], badges: ["Black", "blue"], points: [{points:Bonus:8,}, {points:Bonus:7, }       ]     }  ])
View Code3. Basic Enquiry

MongoDB provides the Db.collection.find () method to perform query operations. The Find method accepts two parameters: one for the query and one for the projected field. Neither of these parameters is required, and if the query condition is omitted, all documents in collection are listed by default.

Db.users.find () // This is equivalent to the above statement Db.users.find ({})
3.1 Equivalent Query

When using the Find () method to perform an equivalent query, you can specify the query criteria by {<field>:<value>} . This condition indicates that all documents that satisfy the value of field are queried in collection. Let's say we need to find all the users with status ' a ', so we can query:

Db.users.find ({status: ' A '})

Query results

{"_id": 3, "name": "Ahn", "age": +, "type": 2, "status": "A", "Favorites": {"artist": "Cassatt", "Food": "Cake" }, "Finished": [6], "badges": ["Blue", "Red"], "points": [{"Points": Bayi, "bonus": 8}, {"Points": "Bonus" ":_id": 6, "name": "ABC", "Age": +, "type": 1, "status": "A", "Favorites": {"Food": "Pizza", "Artis T ":" Picasso "}," finished ": [+]," badges ": [" Black "," Blue "]," points ": [{" points ": +," bonus ": 8}, { "Points": "Bonus": 7}]}
3.2 operator Query

MongoDB supports using operators to construct query conditions, such as comparison operators, such as $GT, $lt, and so on. The query condition using the operator is represented by {<field>: {<operator>:<value>}} . Let's say we want to query the age of more than 22 users, you can do this:

Db.users.find ({age: {$gt: 22}})

Query results

{"_id": 2, "name": "Bob", "Age": $, "type": 1, "status": "A", "Favorites": {"artist": "Miro", "Food": "Meringue "}," finished ": [One, one]," badges ": [" green "]," points ": [{" Points ":" Bonus ": $}, {" Points ":", "Bonu S ": 12 } ] }{ "_id": 4, "name": "XI", "age": the "type": 2, "status": "D", "Favorites": {"artist": "Chagall", "Food": "Chocolat E "}," Finished ": [5, one]," badges ": [" Red "," Black "]," points ": [{" points ": +," bonus ": +}, {" Points ": 51 , "bonus": 15 } ] }{ "_id": 5, "name": "XYZ", "age": +, "type": 2, "status": "D", "Favorites": {"artist": "Noguchi", "Food": "Nougat" }, "Finished": [6], "badges": ["Orange"], "points": [{"points": +, "bonus": 20 } ] }{ "_id": 6, "name": "ABC", "Age": +, "type": 1, "status": "A", "Favorites": {"Food": "Pizza", "Artist": "Picasso" }, "finished": [+], "badges": ["Black", "Blue"], "points": [{"points": +, "bonus": 8}, {"Points": 57, "Bonus": 7}]}
3.3 and relationships

MongoDB supports and relational queries are simple, when a query condition contains multiple <field:value> pairs, the relationship between these conditions is an and relationship. So the query of the and relationship can be represented in this way {<field1>:<value1>, <field2>:<value2>,. ..., <fieldn>:<valuen }. Let's say we want the query to meet the criteria: status is ' D ', and age is greater than 23 users, we can query:

Db.users.find ({status: ' D ', age: {$gt: 23}})

Query results

"_id": 4, "name": "XI", "age": the "type": 2, "status": "D", "Favorites": {"artist": "Chagall", "Food": "Chocolat E "}," Finished ": [5, one]," badges ": [" Red "," Black "]," points ": [{" points ": +," bonus ": +}, {" Points ": 51 , "bonus": 15}]}
3.4 or relationship

MongoDB uses the operator "$or" to support queries for or relationships. The query condition for an or relationship can be structured like this:{$or: [{<field1>:<value1>}, {<field2>:<value2>},..., {<fieldn>: <valuen>}]}. For example, we want to query the status is ' A ' or age greater than 23 users, we can do this:

Db.users.find ({$or: [{status: ' A '}, {age: {$gt: 23}}]})

Query criteria

{"_id": 2, "name": "Bob", "Age": $, "type": 1, "status": "A", "Favorites": {"artist": "Miro", "Food": "Meringue "}," finished ": [One, one]," badges ": [" green "]," points ": [{" Points ":" Bonus ": $}, {" Points ":", "Bonu S ": 12 } ] }{ "_id": 3, "name": "Ahn", "age": $, "type": 2, "status": "A", "Favorites": {"artist": "Cassatt", "Food": "Cake"} , "Finished": [6], "badges": ["Blue", "Red"], "points": [{"Points": Bayi, "bonus": 8}, {"Points": "Bonus" : 20 } ] }{ "_id": 4, "name": "XI", "age": the "type": 2, "status": "D", "Favorites": {"artist": "Chagall", "Food": "Chocolat E "}," Finished ": [5, one]," badges ": [" Red "," Black "]," points ": [{" points ": +," bonus ": +}, {" Points ": 51 , "bonus": 15 } ] }{ "_id": 6, "name": "ABC", "Age": +, "type": 1, "status": "A", "Favorites": {"Food": "Pizza", "Artist": "Picasso" }, "finished": [+], "badges": ["Black", "Blue"], "points": [{"points": +, "bonus": 8}, {"Points": 57, "Bonus": 7}]}
4. Nested document Queries

If the value on a field in a document is also a document, when we need to query the subdocument in this document is worth the time, it involves the query of the nested document. MongoDB supports querying for nested documents.

4.1 Matching entire sub-document

Matching the entire subdocument can be considered an equivalent query, except that this time the value is a sub-document. So the query condition is this {<field>:<sub document>}. Suppose we want to query favorites This field, artist for ' Picasso ', Food for ' pizza ' user, we can do this:

Db.users.find ({favorites: {artist: "Picasso", Food: "Pizza"}})

Query results

{"_id": 1, "name": "Sue", "age": +, "type": 1, "status": "P", "Favorites": {"artist": "Picasso", "Food": "Pizza "}," Finished ": [3]," badges ": [" Blue "," Black "]," points ": [{" Points ": $," bonus ": $}, {" Points ": 85 , "Bonus": 10}]}
4.2 gametes The fields in the document

MongoDB supports matching the fields in the subdocument through the dot (.) Symbol to represent a field in a subdocument, such as we do a query on the artist field in the subdocument in the Favorites field, which can be favorites.artist to represent the artist field in this subdocument

Db.users.find ({"Favorites.artist": "Picasso"})

Query results

{"_id": 1, "name": "Sue", "age": +, "type": 1, "status": "P", "Favorites": {"artist": "Picasso", "Food": "Pizza "}," Finished ": [3]," badges ": [" Blue "," Black "]," points ": [{" Points ": $," bonus ": $}, {" Points ": 85 , "bonus":"_id": 6, "name": "ABC", "Age": +, "type": 1, "status": "A", "Favorites": {"Food": "Pizza"  , "Artist": "Picasso"}, "finished": [+], "badges": ["Black", "Blue"], "points": [{"points": +, "bonus": 8}, {"Points": $, "bonus": 7}]}
5. Querying on an array

If the value of a field in a document is an array type, MONGODB supports constructing a query condition for a field of type group.

5.1 Matching entire array

MongoDB matches the entire array in the same way that it matches the entire nested document. As long as the entire array is given in the condition, just like this {<field>:<value>}, only the <value> here is the entire array that needs to be matched. Suppose we need to find the badges value for "[' Blue ', ' black ']" user, we can do this

Db.users.find ({badges: ["Blue", "Black"]})

Query results

{"_id": 1, "name": "Sue", "age": +, "type": 1, "status": "P", "Favorites": {"artist": "Picasso", "Food": "Pizza "}," Finished ": [3]," badges ": [" Blue "," Black "]," points ": [{" Points ": $," bonus ": $}, {" Points ": 85 , "Bonus": 10}]}
5.2 Finding an element in an array

In addition to the exact match query for the field of the array type, we can also use the elements of the arrays as query criteria, and the main array contains this element, then it will be matched to. For example we need to find all the users in the badges array that contain the ' black ' element, and we can do that

Db.users.find ({badges: "Black"})

Query results

{"_id": 1, "name": "Sue", "age": +, "type": 1, "status": "P", "Favorites": {"artist": "Picasso", "Food": "Pizza "}," Finished ": [3]," badges ": [" Blue "," Black "]," points ": [{" Points ": $," bonus ": $}, {" Points ": 85 , "bonus":"_id": 4, "name": "XI", "Age":, "type": 2, "status": "D", "Favorites": {"artist": "Chaga ll "," Food ":" Chocolate "}," Finished ": [5, one]," badges ": [" Red "," Black "]," points ": [{" points ": +," bonus " : +}, {"Points": Wuyi, "bonus": "_id": 6, "name": "ABC", "Age": +, "type": 1, "status": "A", "Favorite S ": {" Food ":" Pizza "," Artist ":" Picasso "}," finished ": [+]," badges ": [" Black "," Blue "]," points ": [{" Points ": +," bonus ": 8}, {" Points ": $," bonus ": 7}]}

As you can see, the values in the badges field of these three users have a ' black ' element in the array.

5.3 matches the element in the array that specifies the subscript

MONGODB supports constructing query statements with the elements of the specified subscript in the array as query criteria, by using a point number (.) Similar to referencing a subdocument. Refers to the element that specifies the subscript. For example, the first element of an array in a badges field can be expressed as:badges.0, similarly, Nth is badges. N. Suppose we want to find the user that satisfies the first element in the badges array that is ' black ', we can do this:

Db.users.find ({"badges.0": "Black"})

Query results

{"_id": 6, "name": "ABC", "Age": +, "type": 1, "status": "A", "Favorites": {"Food": "Pizza", "Artist": "Picasso "}," finished ": [+]," badges ": [" Black "," Blue "]," points ": [{" points ": +," bonus ": 8}, {" Points ": 57 , "Bonus": 7}]}

The query results see that there is only one user that satisfies the criteria. Although the other user's badges field also has a ' black ' field, the first element that needs to find the array is ' black ', so only one user is eligible.

5.4 array elements specify multiple query criteria and relationships between multiple conditions

MongoDB provides a "$elemMatch" operator whose function is to conditionally match elements in an array, so long as at least one of the elements satisfies the specified condition, then the match succeeds, that is, the condition specified by the ' $elemMatch ' operator is " Relationship with ". To take a look at an example, suppose we want to find the value of an array element that satisfies the finished field is greater than 15, less than 20, we can do this:

Db.users.find ({finished: {$elemMatch: {$gt: $, $lt: 20}})

Query results

{"_id": 1, "name": "Sue", "age": +, "type": 1, "status": "P", "Favorites": {"artist": "Picasso", "Food": "Pizza "}," Finished ": [3]," badges ": [" Blue "," Black "]," points ": [{" Points ": $," bonus ": $}, {" Points ": 85 , "bonus":"_id": 6, "name": "ABC", "Age": +, "type": 1, "status": "A", "Favorites": {"Food": "Pizza"  , "Artist": "Picasso"}, "finished": [+], "badges": ["Black", "Blue"], "points": [{"points": +, "bonus": 8}, {"Points": $, "bonus": 7}]}

As we can see, the use of the "$elemMatch" operator is to match each value in the array with a specified number of conditions, as long as there is at least one value in the array that satisfies the condition we specify, the match succeeds.

The or relationship between multiple conditions

When MongoDB matches an array, it can return the set of results that meet the specified criteria. In layman's terms, the specified condition is a "or" relationship, meaning that if any one of the elements in the array satisfies any one of the multiple query conditions, then the document is considered to be matched. For example, if we specify a query condition like this

Db.users.find ({finished: {$gt: $lt: 20}})

Let's look at the results of the query first

{"_id": 1, "name": "Sue", "age": +, "type": 1, "status": "P", "Favorites": {"artist": "Picasso", "Food": "Pizza "}," Finished ": [3]," badges ": [" Blue "," Black "]," points ": [{" Points ": $," bonus ": $}, {" Points ": 85 , "bonus":"_id": 2, "name": "Bob", "Age": $, "type": 1, "status": "A", "Favorites": {"artist": "Miro  "," Food ":" Meringue "}," finished ": [One, 20]," badges ": [" green "]," points ": [{" Points ": $," bonus ":" "," {"}", "{"} "," {"}," {"] "Points": "Bonus": "_id": 6, "name": "ABC", "Age": +, "type": 1, "status": "A", "Favorites": {"F  Ood ":" Pizza "," Artist ":" Picasso "}," finished ": [+]," badges ": [" Black "," Blue "]," points ": [{" Points ": "Bonus": 8}, {"Points": $, "bonus": 7}]}

This query condition and the above elements match the query criteria compared to the query results we see, in the middle of the record, the value of finished is [11, 25] Also satisfies the query condition. This is because {finished: {$gt:, $lt:}} This condition, which represents any one element in the array, is considered to satisfy the query condition, as long as the content is greater than 15 or less than 20, and the specified condition is a "or" relationship. The relationship between conditions is the relationship between the criteria and the query criteria specified by the $elemMatch operator. So it is not difficult to understand that the value of [11, 25] of the record is matched, because it satisfies 25 is greater than the condition of 15, and 11 is less than the condition of 20, so naturally meet the conditions.

5.5 Queries with sub-documents in the array

When the array contains sub-documents, you can also construct query criteria for the fields in those sub-documents.

Use array subscripts to navigate to specific subdocuments

The query condition in this way is to use both the subscript representation of the array and the dot number (.) of the field in the document. notation to specify a field in a subdocument in an array. It's a bit of a detour, let's take a look at concrete examples.

Db.users.find ({' points.0.points ': {$lte: 55}})

The meaning of this query statement means that we want to query the value of the points field in the Points field, which contains an array of sub-documents labeled 0, satisfying the condition {$lte: 55}, that is, the value of the points field in the subdocument is less than or equal to 55. The query results are as follows:

{"_id": 4, "name": "XI", "Age": "The", "type": 2, "status": "D", "Favorites": {"artist": "Chagall", "Food": "Chocola TE "}," Finished ": [5, one]," badges ": [" Red "," Black "]," points ": [{" points ": +," bonus ": +}, {" Points ": 5 1, "Bonus": 15}]}
Match any subdocument that satisfies a condition

If we omit the subscript for the array, then the query condition becomes

Db.users.find ({' points.points ': {$lte: 55}})

It represents querying points any subdocument in the array, as long as the value of the points field in the subdocument satisfies the condition {$lte: 55}.

Query Result:

{"_id": 3, "name": "Ahn", "age": +, "type": 2, "status": "A", "Favorites": {"artist": "Cassatt", "Food": "Cake" }, "Finished": [6], "badges": ["Blue", "Red"], "points": [{"Points": Bayi, "bonus": 8}, {"Points": "Bonus" ":" _id ": 4," name ":" XI "," Age ":," type ": 2," status ":" D "," Favorites ": {" artist ":" Chagall "," fo Od ":" Chocolate "}," Finished ": [5, one]," badges ": [" Red "," Black "]," points ": [{" points ": +," bonus ": 15}, {"Points": Wuyi, "bonus": 15}] }

As you can see, all records that meet the criteria are included in the query results.

and relationships between multiple conditions

The method of matching the multi-conditional "and" relationships of the arrays mentioned above can also be used to specify multiple matching criteria for the subdocuments in the array. The query condition also takes advantage of the "$elemMatch" operator:

Db.users.find ({points: {$elemMatch: {points: {$lte: +}, bonus:20}}})

As you can see, when you specify multiple matching criteria for a subdocument in a points array, it is similar to specifying multiple matching criteria for elements in the arrays mentioned above. However, the above is to specify the match criteria for the integer, here is the sub-document to specify the matching criteria, and the subdocument in the field can be directly referenced, do not take the dot (.) Referenced in the way of the number.

Query results

{"_id": 3, "name": "Ahn", "age": +, "type": 2, "status": "A", "Favorites": {"artist": "Cassatt", "Food": "Cake" }, "Finished": [6], "badges": ["Blue", "Red"], "points": [{"Points": Bayi, "bonus": 8}, {"Points": "Bonus" ": 20}]}
An or relationship between multiple conditions

Like a query condition that specifies multiple or relationships for an element in an array, a subdocument in an array specifies a query condition for multiple or relationships in a form similar to the statement. Take a look at specific examples:

Db.users.find ({"points.points": {$lte: +}, "Points.bonus": 20})

Here the point (.) is used Number to refer to the field of the subdocument in the array, where two of the conditions are "or" relationships, the meaning of the statement is roughly the same: the query satisfies the value of the points field of any one subdocument in the points array, not less than 70, or a record with a value of 20 for any of the bonus fields of a subdocument. The result of the query is this:

{"_id": 2, "name": "Bob", "Age": $, "type": 1, "status": "A", "Favorites": {"artist": "Miro", "Food": "Meringue "}," finished ": [One, one]," badges ": [" green "]," points ": [{" Points ":" Bonus ": $}, {" Points ":", "Bonu S ":_id": 3, "name": "Ahn", "age": $, "type": 2, "status": "A", "Favorites": {"artist": "Cassatt", " Food ":" Cake "}," finished ": [6]," badges ": [" Blue "," Red "]," points ": [{" Points ": Bayi," bonus ": 8}, {" Points ":", "Bonus": 20}]}

If we specify the subscript for an array, you can define the position of the element in the above multiple "or" conditions. Like what:

Db.users.find ({' points.0.points ': {$gte: +}, ' Points.0.bonus ': 8})

This is used to specify an element in the array by specifying the subscript in the array.

Query results

{"_id": 3, "name": "Ahn", "age": +, "type": 2, "status": "A", "Favorites": {"artist": "Cassatt", "Food": "Cake" }, "Finished": [6], "badges": ["Blue", "Red"], "points": [{"Points": Bayi, "bonus": 8}, {"Points": "Bonus" ":_id": 6, "name": "ABC", "Age": +, "type": 1, "status": "A", "Favorites": {"Food": "Pizza", "Artis T ":" Picasso "}," finished ": [+]," badges ": [" Black "," Blue "]," points ": [{" points ": +," bonus ": 8}, { "Points": "Bonus": 7}]}
6. Summary

Here we are almost done with the syntax for query statements in MONGO. From queries on simple values, to queries on nested sub-documents, to array queries, to complex queries nested in arrays and sub-documents. And how to do "or" operations and "and" operations on multiple query criteria. I hope this article will be of some help to you.

Speak so much, light look useless, or to do more hands-on practice, their own to knock over the code will deepen the impression, if you can in the project business scenarios need to use these queries, then the better. Because this will make these knowledge better absorbed, otherwise it will fall into the school forget, forget to learn the abyss. This is actually the benefits of blogging, learning new knowledge, even if you can not immediately use the work, through a blog to consolidate the deepening impression, although not in the actual project used to produce good results, but also has a certain effect.

MongoDB's query operation

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.