Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the basic query condition operators of MongoDB

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

Shulou(Shulou.com)06/02 Report--

What are the MongoDB basic query condition operators, many novices are not very clear about this, in order to help you solve this problem, the following editor will explain for you in detail, people with this need can come to learn, I hope you can gain something.

Brief introduction

The find function is used in MongoDB to make queries. The query finally returns a subset of the documents in a collection, which includes 0 documents to all documents in the collection.

[first query parameter]

The first argument to the find function is a document that gives a description of what documents we want to query in the collection. If we want to query all documents, we can call the find function without any parameters, or the first parameter is an empty document {}, as in the following example:

How do we understand the first document that represents the query parameters? For example, we execute db.people.find ({"age": 18}). This function actually indicates that we want to query documents with a key "age" with a value of 18. Documents whose key "age" is not equal to 18 or that do not exist will not be queried. For example, we execute this function: db.people.find ({"name": "jimmy", "age": 18}), which actually represents the document where the value of the query key "name" is "jimmy" and the value of the key "age" is 18, that is, the relationship between the conditions in the query document is AND!

When using the first parameter, we need to note that the value in the "key-value pair" in the query document must be constant!

[second query parameter]

In the above example, we do not specify or only specify the first parameter of the find function to query the resulting document, which will contain all the key-value pairs of the original collection document. This situation does not apply to some key values for a particularly large number of documents, because we may only be concerned with a few key-value pairs in that document. At this point, we can use the second parameter of the find function to specify the returned key-value pair, which can also reduce the amount of data transferred and speed up the efficiency. The second parameter is also a document, as in the following example:

Using the second parameter of the find function, we have these things to note for this document:

1 "for all keys that are not" _ id ", the value is either not equal to 0 at the same time (indicating that the key-value pair is to be queried) or equal to 0 at the same time (indicating that the key-value pair is to be ignored), otherwise an error is performed.

2 "for all keys that are not" _ id ", if all their values are 0, then if the key" _ id "is also specified at this time, the value of the key" _ id "must be 0, otherwise an error message will be performed.

3 "for the key" _ id ", if you do not specify its value, the key-value pair must be included in the query result. If you do not want to include it, you can specify that its value is 0.

To sum up, let's sum up that if we need to use the second parameter, the technique used is to specify that the value of all the keys you need is a number other than 0, and if we also want to filter the key "_ id", then specify that the key value of "_ id" is 0.

[query conditions]

The query conditions mentioned above all match exactly, that is, how much is "=". There are obviously more complex matches for queries in MongoDB. Such as scope, OR clause and inversion, etc. Let's introduce them separately.

"$lt", "$lte", "$gt", and "$gte" are all range comparison operators that correspond to =. By combining them, you can query documents with values in a certain range, for example, we want to query all users aged 18-30 (inclusive):

This range query operator is not only used on keys with numeric values, but also is particularly useful for range matching of keys with values of dates! For example, if we want to query the information of users whose registration date is before 2007-05-01, we can write:

Sometimes we need to query documents where a key is not equal to a value, and we can use the conditional operator "$ne", which means unequal. For example, to query documents whose registered user name is not equal to "tom":

The conditional operator "$ne" applies to all types of values!

[OR query]

There are two ways to query OR in MongoDB: "$in" can be used to query multiple values of a key, while "$or" is more generic and can be used to complete the combination of multiple key-value pairs. Let's also demonstrate separately: we want to look up the names of all bettors whose lottery numbers are 10, 10, 20, and 30:

However, if we are also asked to find out all the betting information with the lottery number 10 in 20 no. 30 or the punter's name "tim", we cannot do it simply with "$or". We can use the operator "$or" and the "$or" operator to combine the conditions cobbled together by other operators such as "$in":

Use the "$or" operator, whose value is an array of conditions that are finally combined by or. A best practice for using this conditional operator is to put the loosest conditions first, which can speed up document matching!

[$mod and $not]

The $mod operator, using the format {"key": {"$mod": [num1, num2]}}, queries the value of the "key" against num1. If this value is equal to num2, the entire document meets the criteria. For example, we want to query all users in their current year (age is an integral multiple of 12):

$not is a meta-condition, that is, it can be used on any other condition, indicating that it is reversed, or the above example. This time, we need to check the information of all user documents that are not in their current year:

The $not conditional character is very powerful in conjunction with regular expressions, so let's make a prediction here, and we'll talk about queries that introduce regular expressions later.

[type-specific query]

When querying a document with a key whose value is null, we will find a strange phenomenon. Let's first look at an example:

It seems possible to query the correct document using the condition with a value of null, but we ignore what happens if there is a document in the collection without the key "y":

Sure enough, documents without this key also match the condition null. If we need to filter out such documents, we need another conditional operator, $exists, to indicate that the key must exist:

We found that because there is no equivalent conditional operator like "$eq" in MongoDB, the judgment of "= null" can only be achieved by {"$in": [null]}!

[regular expression]

Regular expressions are a powerful tool for manipulating strings in any language! In the query of MongoDB, its power remains undiminished. Regular expressions have the flexibility to match values of string types. For example, we want to query all user documents whose names begin with "喜悦" and ignore upper and lower case:

Regular expressions are written in the same way in Shell as in JavaScript, and regular expressions are written between a pair of "/ /". Some writing methods of specific regular expressions you can refer to the relevant specifications of regular expressions. We mentioned above the combination of the operator $not and regular expressions, which we will demonstrate here:

We can see that using $not is the key that uses it as a regular expression, indicating that it does not match this regular expression. As we explained earlier, MongoDB supports regular expressions as a data type, that is, values are allowed to be regular expressions in key-value pairs, and regular expressions can also match successfully for such key-value pairs:

However, note that the matching of the regular expression must be an exact match, that is, the regular expression is written in exactly the same way in order to match successfully (which will not be encountered in practical applications).

MongoDB can use indexes for prefixed regular expression (/ ^ joe/i) queries, so this prefixed regular table query is fast!

Here again slightly mention the difference between the find function and the findOne function, just said that the find function returns a subset, while findOne returns a document or null (no results are found). For some functions that can accept documents as parameters, such as insert, you can directly use the return value of findOne as a parameter.

Finally, we summarize the basic query condition operator, because we mentioned earlier that the modifier operator also starts with "$", such as "$set", "$inc", etc., and the query condition operator introduced here also starts with "$". What are the differences in use? The modifier operators are the keys of the outer document, while the operators of the query condition are basically the keys of the inner document (note that "$or" is an exception).

Is it helpful for you to read the above content? If you want to know more about the relevant knowledge or read more related articles, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Internet Technology

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report