This article mainly introduces MongoDB Detailed explanation of various query operations , Including comparison query 、 Relational query 、 Array query, etc , Friends in need can refer to

One 、find operation

MongoDB Use in find To query , By designation find The first parameter of can realize all and part of the query .

1、 Query all

Empty query document {} Will match the entire contents of the collection . If you do not specify a query document , The default is {}.

2、 Partial query

3、 Key screening

Key filtering is to return only the key values that you are interested in when querying , By designation find To achieve . This can save the amount of data transferred , It can also save the time and memory consumption of client decoding documents .

When inquiring , The value of the query document concerned by the database must be constant .

Two 、 Query criteria

1、 Comparison query

$lt,$lte,$gt,$gte,$ne and <,<=,>,>=,!= It's one-to-one , They can be combined to find a range of values .

2、 Relational query

$in Used to query multiple values of a key ,$nin Will return documents that do not match any of the criteria in the filter array . take $in And $not Combination can achieve $nin Same effect .

$or Used to do... On multiple keys or Inquire about .

3、 ... and 、 Specific types of queries

1、null Inquire about

null Not only can it match itself , It can also match documents where the key does not exist .

2、 Regular expressions

3、 Array query

$all: Matching arrays with multiple elements .

$size: Query an array of specified length .

$slice: Returns a subset of an array .

4、 Embedded document query

Four 、$where Inquire about

$where Query is MongoDB The advanced query section of , Can execute any JavaScript As part of the query , It is a supplement to other query methods .

$where The query needs to take each document from BSON Convert to JavaScript object , And then through $where To run , The process cannot take advantage of indexes , So query speed It's much slower than regular query . If it has to be used , You can use regular queries as prefilters , If you can use index, you can use index according to non $where Clause to filter , Finally using $where Tune the results . Another way is to simplify by mapping -MapReduce.

5、 ... and 、 The cursor

Cursors are very useful things ,MongoDB The database uses a cursor to return find The results of the implementation of . The client can control the final result effectively by using cursor , Like paging , Sort .

1、limit,skip and sort

limit: Limit the number of results , The limit is the upper limit .
skip: Skip the match to the front n A document , Then return to the remaining documents .skip Skipping too many documents can cause performance problems , It is suggested that .
sort: Sort documents by the specified key ,1 In ascending order ,-1 For the descending order .

2、 Advanced Query options

Packaging query : Use sort,limit or skip Further control of the final results .

Useful configuration options :

$maxscan:integer, Specify the maximum number of documents to be scanned by the query .
$min:document, The start condition of the query .
$max:document, The end condition of the query .
$hint:document, Specify which index the server uses for the query .
$explain:boolean, Get the details of query execution ( The index used , The number of results , Time consuming, etc ), Instead of actually executing the query .
$snapshot:boolean, Ensure that the result of the query is a consistent snapshot at the moment the query is executed , To avoid inconsistent reads .

Wrapping a query will wrap the query criteria into a larger query document , For example, when executing the following query :{"name":"bar"}).sort("x":1)

shell The query will be sent from {"name":"bar"} convert to {"$query":{"name":"bar"},"$orderby":{"x":1}}, Not directly {"name":"bar"} Send to database as query document .

3、 Inside the cursor
Two ways to look at cursors : The client cursor and the database cursor represented by the client cursor ( Server side ).

On the server side , Cursors consume memory and other resources , So we need to release as soon as possible under reasonable circumstances . The server side causes cursor termination as follows :

1、 The cursor is automatically cleared when it completes the iteration of the matching result .

2、 When the client is out of scope , The driver sends special messages to the server , Let it destroy the cursor .

3、 Destroy over time , have access to immortal Function close cursor timeout , In this operation, the cursor must be closed after the iteration .

6、 ... and 、 summary

Use MongoDB We need to design the document structure reasonably , To meet certain specific needs . For example, randomly selecting documents , Use skip Skip a random document without adding a random key to it , Then use a random number to query the document , Random keys can also add indexes , More efficient . Reasonable choice , Reasonable design .

MongoDB Various query operation details of more related articles

  1. Django frame And ORM Query operation details

    Django frame And ORM Query operation details Browse the catalog General operation ForeignKey operation ManyToManyField Aggregate query Group query F Query and Q Inquire about Business Django Terminal printing SQL sentence stay Py ...

  2. Python operation Mysql Database advanced —— Query operation details ( One )

    As we have mentioned before, in Python3.x How to connect a Mysql database , And how to create a table for this database , Add, delete, and look up the data in the table . You must be right Mysql Databases and simple sql Have a certain understanding of the sentence , Actually sql Statement blog ...

  3. mongodb Study 04 Operation details (2)

    Search for documents Filter to find db.collection.find(); Returns a subset of documents in a collection , Subset of Range from 0 Document to the entire collection ; db.collection.findOne(); Returns a filtered document ; ...

  4. mongodb Study 03 Operation details

    Inserted into the document db.test.insert({"name":"jinks"}); Batch insert db.test.insert([{}, {}, {}]); A batch insert ...

  5. mongodb Study 05 Operation details (3)

    Advanced Query options // Simple query var cursor ={"foo" : "bar"}) // Encapsulating queries var cursor = db.f ...

  6. Django And ORM Query operation details

    Browse the catalog General operation ForeignKey operation ManyToManyField Aggregate query Group query F Query and Q Inquire about Business Django Terminal printing SQL sentence stay Python Call in script Django Environmental Science Other exercises ...

  7. hibernate( 7、 ... and ) hibernate In the inquiry way detailed explanation

    preface Previous pair hibernate Queries in are always confused , I don't know what's in it . Because of the lack of summary . Before reading this article , What you should know is some query operations in the database , Multi table query, etc , If you don't understand , You can go and have a look first MySQL Count ...

  8. [Android Rookie zone ] SQLite Operation details --SQL grammar

    The article is completely excerpted from : Peking blue bird [Android Rookie zone ] SQLite Operation details --SQL grammar  : SQLite The library can solve ...

  9. windows phone 8.1 Development SQlite Detailed explanation of database operation

    Original text : This article will share with you WP8.1 in SQlite Basic operation of database :( Finally, there is the source code of the whole example )( Hope to pass this ...

Random recommendation

  1. Double and double The difference between

    1.Double yes java Defined classes , and double Is a predefined data type (8 One of the species )2.Double It's like being right double Type of packaging , There are many ways to do it String To double Transformation , And get all kinds of d ...

  2. Quartz Application of framework

    This article will briefly introduce in the absence of Spring When .. How to use Quartz... Skip here Quartz Other introductions of . If you want to know more about Quartz, You can click to download Quartz Help document for . Quar ...

  3. Another little regular replace

    var a = ""; var b = " ...

  4. var obj = {};var obj2 = [];var obj3;

    <script> var obj = {}; console.log(obj); var obj2 = []; console.log(obj2); var obj3; console.l ...

  5. sql The batch 、 Gain from growth 、 Business 、 Big text processing

    The batch Batch execution is required sql sentence ! demand : Save information in bulk ! Design : AdminDao Public void save(List<Admin list){ // Now in this way // loop // Protect ...

  6. Smart.coder Daily Scrum Meeting 08

    Standing conference content : Improve the search function of small programs , I'm going to consider the function of automatic information input classification . 1. Standing meeting photos : 2. Mission board 3. Burnout figure

  7. ERP Regional management in China

    Regional management Regional management mainly realizes the addition of regional data . edit . see . Enable . Disable and other functions , In addition, it also contains the encapsulation of region selection control . Business function point : Regional data view : The area list is displayed in a tree , Add provinces to the list . City . District . county . Township icon . Region selection control : choice ...

  8. use JavaScript Write a simple calculator

    This article USES the js Realized a simple add . reduce . ride . Except the calculator . Here are css Part of the code : *{ padding:0; margin:0; color: #424242; } .outer{ width:300px; ...

  9. qml: Custom buttons -- Imitation QML Own control ;

    import QtQuick 2.0 Rectangle { id: btn; width:; height:; radius:; border.color: "#A3A3A3"; ...

  10. Python Medium string Module learning

    Code based , Believe there is python I can understand the basic : ? [python] view plain copy >>> import string   >>> string.a ...