当前位置:网站首页>My name is Mongo. I've received the "basic query article". It's worth having

My name is Mongo. I've received the "basic query article". It's worth having

2020-11-09 14:08:08 The journey of programmer training

This is a mongo Second articles 「 Basic section of query 」, It will be updated continuously 6 piece

 

  mongodb There will be a series of articles on the summary of the article , The order is to learn how to use it first , Learning how to use it well , Stop being impatient and impetuous , Step by step , Follow me to explore communication .

   Through the introduction of the last basic article , I believe you have a preliminary understanding of me , And it's easy to use me , In the process of use, I believe that you use the most query bar , Today, I'd like to sum up the query basis with you . If there is something wrong with the summary , I hope you can give me more advice .

01: Query introduction

   Inquire about mongdodb Two methods are provided :find() and findOne(), The former is to query all data that meets the requirements , The latter only queries the first data that meets the requirements , Both have the same parameters , There are two parameters , And both parameters are optional .

   Command format :db.collection.find(query,projection)  , Both parameters are not required .

  query: Is a query condition BJSON object , According to the query conditions, the corresponding BJSON object . Such as :

db.user.find({name:"name Corresponding value "},{sex:"sex Corresponding value "})

 

       projection: Set the set of fields to be returned by the query , Do not set to return all fields , The format for :{ Field name : Whether to obtain ..}, When set to 1 Representatives need to get , Be careful :_id The default value is 1, So you need to query the results, you don't need to _id, Then you need to set the value to 0.

   I still feel a little empty in terms of myself , Let's go back to the last example !

   Data initialization :

   To the database testdb Of user The collection initializes the following three pieces of data

use testdb
db.user.insert([{name:" The journey of foreman's cultivation ",age:2,from: "CTU"},
                {name: "mongdo",age:13,from: "USA"},
                {name: "C++",from: "USA" ,author:["xiaoxu","xiaozhang"]}])

 

   Data query instance :

//  Query all data 
db.user.find()
//  Query results : Returns the just initialized 3 Data, all data   
​
//  Inquire about name= Programmer training tour , And only return nodes  name and from
db.user.find({name:" The journey of foreman's cultivation "},{_id:0,name:1,from:1})
//  The query result is :
{ "name": " The journey of foreman's cultivation ","from": " CTU" }
​
// Query all the data , And only return nodes  name and from
db.user.find({},{_id:0,name:1,from:1})
//  Query results 
[{"name": " The journey of foreman's cultivation ","from": "CTU"},
{"name": "mongdo","from": "USA"},
{"name": "C++","from": "USA"}]//  Query only one piece of data , And two other parameters find The method has been , Not in detail 
db.findOne()

  

   Basic query summary , Through the above example operation , It's not hard for us to find out :

  1、find and findOne Use the same ,findOne Look up a ,find Query all

  2、 The query has two parameters , And both parameters are not required

  3、projection When setting ,_id Default return , If you do not return, you need to manually set it to 0

02: Query condition exploration

     Through the introduction of the inquiry, we should have a preliminary impression of the query , Maybe you wonder , The inquiry is so simple , Can't solve the actual work needs , For example, the query age is in 20-30 Between users . No hurry, no hurry , The following exploration is to solve these problems .    

Let's start with a simple single query symbol , Master a single query symbol , As for the complex query conditions, it is very simple , Just like building blocks, you can assemble according to the rules .

The command format of a single query character is :db.collection.find({ Field :{ Query character : value }})

  mongodb The individual query characters of include :

   Comparison symbol ( be equal to [ Strictly speaking, it is not a query character ]、 It's not equal to 、 Greater than 、 Less than 、 Greater than or equal to 、 Less than or equal to );

   The inclusion character ( contain 、 It doesn't contain 、 All inclusive ); Fuzzy matchers ( Left match 、 Right match 、 Fuzzy matching 、 All match );

   Element operators ( Whether the field exists 、 Whether the field value is empty 、 Field type );

   Set querier ( length 、 Subquery );

   The modulo ;

   Regular expressions .

   Haha, just to make it clear , That's what it says 7 A query is my own summary category , If there is something wrong , Give me a lot of advice . Sum up , It is found that there are many query symbols , Next, we will introduce the use of each query character : The following example continues to use the database operation in the example above .

   Initialize the database :

db.user.insert({name:".net",age:88,author: ["xiaoxu","xiaozhang","xiaoliu"]})

 

NO.1 【 Comparison symbol 】

Symbol :$ne ( It's not equal to )

explain : And equal to just the opposite , Include document data without this field

grammar : {field:{$ne:< value >}}

example :

//  Inquire about from!="USA" The data of 
db.user.find({from: {$ne: "USA"}})
//  The results showed that the foreman's training journey and .net Two pieces of data 

 


Symbol :$gt( Greater than )

explain : For documents with field type numbers , Document data whose value is greater than the specified value

grammar :{field:{$gt:< value >}}

example :

//  Inquire about age>13 The data of 
db.user.find({age: {$gt:13}})
//  It turns out that only .net A piece of data 

 


Symbol :$gte ( Greater than or equal to )

explain : For documents with field type numbers , Document data whose value is greater than or equal to the specified value

grammar :{field:{$gte:< value >}}

example :

//  Inquire about age>=13 The data of 
db.user.find({age: {$gte:13}})
//  It turns out that mongo and .net Two pieces of data 

 


Symbol :$lt( Less than )

explain : For documents with field type numbers , Document data whose value is less than the specified value

grammar : {field:{$lt:< value >}}

example :

//  Inquire about age<13 The data of 
db.user.find({age: {$lt:13}})
//  Only one piece of data about the cultivation journey of the foreman was found 

 


Symbol :$lte( Less than or equal to )

explain : For documents with field type numbers , Document data whose value is less than or equal to the specified value

grammar : {field:{$lte:< value >}}

example :

//  Inquire about age<=13 The data of 
db.user.find({age: {$lte:13}})
//  The results showed that the foreman's training journey and mongo Two pieces of data 

 

NO.2 【 The inclusion character 】

Symbol :$in( contain )

explain : If the field to be queried is not a set , The value of the field to be queried is in the condition set ; If the field to be queried is a set , Then only one of the fields to be searched is included in the condition set .

grammar : {field:{$in:[ value 1, value 2..]}}

example :

//  Inquire about from stay ["CTU","USA"] The data of 
db.user.find({from: {$in:[ "CTU","USA"]}})
//  The result inquires the preface member to practice the journey 、mongo and c++ Three pieces of data ​

//  Inquire about author stay ["xiaoxu"," xiaowang"] The data of 
db.user.find({author:{$in:["xiaoxu","xiaowang"]}})
//  The result inquires the preface member to practice the journey 、mongo Two pieces of data 

 


Symbol :$nin( It doesn't contain )

explain : And inclusion is just the opposite , The query results include two types of data : There is this field , But the values of this field are all in the document data in the condition set ; No document data for this field .

grammar :{field:{$nin:[ value 1, value 2..]}}

example :

//  Inquire about from be not in ["CTU","USA"] The data of 
db.user.find({from: {$nin:[ "CTU","USA"]}})
//  It turns out that only  .net  A piece of data 

​//  Inquire about author be not in ["xiaoliu","xiaowang"] The data of 
db.user.find({author:{$nin:["xiaoliu","xiaowang"]}})
//  The result inquires the preface member to practice the journey 、mongdo and c++ Three pieces of data 

 


Symbol :$all( All inclusive )

explain : It's very similar to inclusion , Inclusion is a subset of total inclusion , All include only the field to be queried contains all the values of the query criteria . It is mainly used for document data query with set fields

grammar :{field:{$all:[ value 1, value 2..]}}

example :

//  Inquire about author All contain ["xiaoxu","xiaozhang"] The data of 
db.user.find({author:{$all:["xiaoxu","xiaozhang"]}})
//  It turns out that c++ and .net Two data 

​//  Inquire about author All contain ["xiaoxu","xiaoliu"] The data of 
db.user.find({author:{$all:["xiaoxu","xiaoliu"]}})
//  As a result, none of the data met the requirements 

 

NO.3 【 Fuzzy matchers 】

     Fuzzy query corresponds to SQL Medium like Inquire about ,mongodb Fuzzy query through / Conform to achieve , and SQL Medium % Corresponding , In fact, fuzzy query is a short form of regular expression , I don't say much nonsense , Go straight to the case !

Symbol :/^X/ ( Left match )

explain : Match with X All the aggregate data that started

example :

//  Inquire about name  With   cheng   The starting set of data 
db.user.find({name:/^ order /})
//  It turns out that only   The journey of foreman's cultivation   A piece of data 

 


Symbol :/X$/( Right match )

explain : Match with X All aggregate data that ends

example :

//  Inquire about name  With   brigade   End of set data 
db.user.find({name:/ brigade $/})
//  It turns out that only   The journey of foreman's cultivation   A piece of data 

 


Symbol :/X/ ( Fuzzy matching )

explain : Matching inclusion X All the aggregate data of

example :

//  Inquire about name  With   The programmer   The aggregate data of 
db.user.find({name:/ The programmer /})
//  It turns out that   The journey of foreman's cultivation   A piece of data 

 


Symbol :/^X$/( The whole match )

explain : Since X It starts with X All set data at the end , In fact, it is equal to X Data set for ; Equivalent to ”X”

example :

//  Inquire about name = The journey of foreman's cultivation   The aggregate data of 
db.user.find({name:/^ The journey of foreman's cultivation $/})
//  It turns out that   The journey of foreman's cultivation   A piece of data 

 


Symbol :i( Case insensitive )

explain : Add... After the fuzzy matching degree i Case insensitive during matching

example :

//  Inquire about from It includes t The data of , Include t and T
db.user.find({from:/t/i})
//  It turns out that   The journey of foreman's cultivation   A piece of data 

 

NO.4 【 Element operators 】

 

For demonstration , Query a new piece of data

db.user.insert({name:"java",age:" A secret ",author:null})

 

 Symbol :$exists( Whether the field exists )

explain : The corresponding value is bool, When it comes to true: Find the document data with the modified field ( The value of the include field is empty );false: Query the document data that does not exist to change the field

grammar :{field:{$exists:<boole>}}

example :

//  The query contains author The aggregate data of 
db.user.find({author:{$exists:true}})
//  Query out c++、.net、java Three pieces of data 

​//  The query does not contain author The aggregate data of 
db.user.find({author:{$exists:false}})
//  Find out the pilgrimage of the foreman 、mongdo Two pieces of data 

 


Symbol :null( Whether the field value is empty )

explain : Query two types of data , There is no document data of the node and there is a change node, but the data is null Document data . relative $exists:false Another class of values is null Document data

grammar :{field: null }

example :

db.user.find({author: null })
//  Find out the pilgrimage of the foreman 、mongdo、java Three pieces of data 

 


Symbol :$type( Field type )

explain : Query according to the type of field , The specific field type is an enumeration value , Please check the relationship of enumeration values on the Internet , Not here !

grammar :{field:{$type:< Type enumeration value number>}}

example :

//  Inquire about age Document data for numerical values 
db.user.find({age:{$type:1}})
//  It turns out that   The journey of foreman's cultivation 、mongdo、.net  Three pieces of data 

​//  Inquire about age Document data for Strings 
db.user.find({age:{$type:2}})
//  It turns out that java  A piece of data 

NO.5 【 Set querier 】

Initialize a piece of data : 

db.user.insert({name:"python",author:[{authorName:" Wang Qiang ",date:"2020-11-06"},{authorName:" Liu Qiang ",date:"2020-11-01"}]})

  Symbol :$size( length )

explain : For data whose node data is a subset , Query the subset length of the corresponding node

grammar :{fild:{$size:<numbr>}}

example :

//  Inquire about author The length of is 3 The data of 
db.user.find({author:{$size:3}})
//  Query out .net A piece of data 

​//  Inquire about author The length of is 1 The data of 
db.user.find({author:{$size:1}})
//  No data was found 

 


Symbol :$elemMatch( Subquery )

explain : The specific query conditions of subquery are the same as those above , It's just a nested query , Query the sub query document data with data

grammar :{fild:{$elemMatch:{ Subquery criteria }}}

example :

//  Inquire about author Medium authorName For Wang Qiang's data 
db.user.find({author:{$elemMatch:{authorName:" Wang Qiang "}}})
//  It turns out that python A piece of data 

 


Subquery extension

explain : Subquery syntax also supports outer nodes . Child node pattern .

grammar :{" Outer node . Child node ": Subquery criteria }

example :

//  Inquire about author Medium authorName For Wang Qiang's data 
db.user.find({author.authorName:" Wang Qiang "})
//  It turns out that python A piece of data 

 


NO.6 【 The modulo 】

Symbol :$mod( modulus )

explain : In short, it is to query the remainder of a number

grammar :{fild:{$ mod:[value,value2]}}

example :

//  Inquire about age except  3  Remainder is 2 The data of 
db.user.find({age:{$mod:[3,2]}})
//  Find out a piece of data of the foreman's cultivation journey 

NO.7 【 Regular expressions 】

Symbol :$regex( Regular matching )

explain :mongodb Regular matching in queries and js The regular matching in is consistent , If it will js It's easy to get started with regular matching in . Several key words and their attention :

    1、^ The meaning of taking the opposite , To use a special escape character, you need to precede it with a slash ;

    2、 adopt ^ Take the opposite , Re pass $not Take the opposite , You can get only one type of data

    \\d  Numbers

    \\s  Space

    \\w  Numbers and letters

grammar :{fild:{$ regex: Regular expressions , $options: "options value " }}

     among $options The matching rules can be changed , It's a number of fixed enumeration values (i,m,x,s), But different enumeration values can be used in combination , The specific enumeration values are as follows :

     i:  Ignore case ;

     m:  Multi line matching pattern , Will change ^ and $ Default behavior of metacharacters , Match the beginning and end of the line, respectively , Instead of matching the beginning and end of the input string .

    x:  Ignore non escaped white space characters , Non escaped white space characters in regular expressions are ignored , At the same time, the well number (#) To be interpreted as the beginning of a note , Can only be explicitly located in option In the options .

    s:  Single line matching pattern , Will change the dot in the pattern (.) Default behavior of metacharacters , It will match all the characters , Include line breaks (\n), Can only be explicitly located in option In the options .

//  List several common query methods in daily work 

//  Inquire about  name Contained in the   Capital letters  O The data of , Case sensitive 
db.user.find({age:{$regex:"O"}})
//  No data was found 

​//  Inquire about  name Contained in the   Capital letters  O The data of , Case insensitive 
db.user.find({name:{$regex:"O",$options:"$i"}})
//  Query out  mongdo、python Two pieces of data 

​//  Inquire about from In the field, use C Start U Data at the end 
db.user.find({from:{$regex:"^C\\wU$"}})
//  Find out a piece of data of the foreman's cultivation journey 

​//  Inquire about age Including Chinese data 
db.user.find({age:{$regex:"[\u4e00-\u9fa5]"}})
//  Result value query java  A piece of data 

​//  Inquire about age Data not included in Chinese 
db.user.find({age:{$not:{$regex:"[\u4e00-\u9fa5]"}}})
//  Find out the foreman's training journey 、mongdo、C++、.net、python​

//  Inquire about name Data that contains only letters ,^  The meaning of taking the opposite 
db.user.find({"name":{$not:{$regex:"[^a-zA-z\\s]"}}})
//  Query out mongdo、java、python  Three pieces of data 

​//  Inquire about name Data containing only Chinese characters , Can contain spaces 
db.user.find({"name":{$not:{$regex:"[^\\s\u4e00-\u9fa5]"}}})
//  Just find out   Programmer training tour   A piece of data 

03: Summary

     Okay , This article concludes with this , Through the summary of this article , Yes mongodb The operation of single query operator has a relatively clear cognition and practice , Of course, the actual use of queries is more than that simple , There are also logical queries with single lookup combinations , Other functions that already correspond to ( Number of pieces 、 Paging query, etc ), Follow up with a special article to summarize and share . Welcome to continue to pay attention .

 

END
Originality is not easy. , Thanks for scanning support , Get more , thank you :

Click on a recommendation , You'd better see

版权声明
本文为[The journey of programmer training]所创,转载请带上原文链接,感谢