MongoDB native statement exercise: official website example

preface

As mentioned earlier, after practicing for a long time, I found that the official brought its own demo, followed by the official website again, and learned more operators. Then I'll see if I have time to practice some more

Learning method: before running those topics with specific values, you can imagine the approximate values in advance, and finally run to see whether the results are consistent with the expected results

Each of the following statements can be directly copied to the Navicate and MongoDB shell for execution

1, Query document - Basic

// Official documents 
// -------------------------------------------------------------------------------Query document - Basic
// insert data
db.inventory.insertMany([
   { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
   { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
   { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
   { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
   { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
])

// Query all
db.inventory.find()
db.inventory.find({})

// Specify equality condition - select all documents "D" with status equal to from the inventory collection:
db.inventory.find({status: "D"})

// Use the query operator to specify criteria - retrieve all documents with status equal to "A" or "D" from the inventory collection
db.inventory.find({status: {$in: ["A", "D"]}})
db.inventory.find({$or: [{status: "A"},{status: "D"}]})

// Specify AND condition - retrieves all documents in the inventory collection with status equal to "A" AND qty less than ($lt) 30
db.inventory.find({status: "A", qty: {$lt: 30}})
db.inventory.find({$and: [{status: "A"},{qty: {$lt: 30}}]})

// Specify OR condition - retrieves all documents in the collection whose status is equal to "A" OR whose qty is less than ($lt) 30
db.inventory.find({$or: [{status: "A"},{qty: {$lt: 30}}]})

// Specify AND and OR conditions - select all documents in the collection from the query documents, where status="A" AND any qty less than ($lt) 30 OR item start with the character p: 
// Here {item: /^p /} after debugging for a long time, I found that my receipt was bracketed {item: "/^p /}. This expression cannot be bracketed
db.inventory.find({status: "A", $or: [{qty: {$lt: 30}},{item: /^p/}]})

// From here, expand to query document - regular to expand some regular correlation

2, Query document - array

// -------------------------------------------------------------------------------Query document - array
// insert data

db.inventory.insertMany([
   { item: "journal", qty: 25,tags: ["blank", "red"], dim_cm: [ 14, 21 ] },
   { item: "notebook", qty: 50, tags: ["red", "blank"], dim_cm: [ 14, 21 ] },
   { item: "paper", qty: 100, tags: ["red", "blank", "plain"], dim_cm: [ 14, 21 ] },
   { item: "planner", qty: 75, tags: ["blank", "red"], dim_cm: [ 22.85, 30 ] },
   { item: "postcard", qty: 45, tags: ["blue"], dim_cm: [ 10, 15.25 ] }
]);

// Clear data
db.inventory.drop()

// The field tags value is an array containing exactly two elements, "red" and "blank", in the specified order:

db.inventory.find({tags: ["red", "blank"]})

// If you want to find an array "blank" containing the elements "red" and ", regardless of the order or other elements in the array, use the $all operator

db.inventory.find({tags: {$all: ["red","blank"]}})

// To query whether the array field contains at least one element with the specified value
db.inventory.find({tags: "blue"})

// To specify conditions for elements in an array field, for example, query the array dim_cm contains at least one document with a value greater than (no value) and greater than or equal to 30
db.inventory.find({dim_cm: {$gte:30}})

// Range lookup array 10-15, one condition is satisfied
db.inventory.find({dim_cm: {$gt:15, $lt: 20}})

// The range lookup array conditions are all met
db.inventory.find({dim_cm: {$elemMatch: {$gt:15, $lt: 20}}})

// Using point notation, you can specify query criteria for elements at a specific index or location of an array.
db.inventory.find({"dim_cm.1": {$gt: 25}})

// Query documents based on array size
db.inventory.find({dim_cm: {$size:2}})

3, Query documents - embedded / nested documents

// -------------------------------------------------------------------------------Query nested documents

// insert data
db.inventory.insertMany([
    { item: "journal", qty: 25, size: { h: 14, w: 21, uom: "cm" }, status: "A" },
    { item: "notebook", qty: 50, size: { h: 8.5, w: 11, uom: "in" }, status: "A" },
    { item: "paper", qty: 100, size: { h: 8.5, w: 11, uom: "in" }, status: "D" },
    { item: "planner", qty: 75, size: { h: 22.85, w: 30, uom: "cm" }, status: "D" },
    { item: "postcard", qty: 45, size: { h: 10, w: 15.25, uom: "cm" }, status: "A" }
])

// The following query selects all documents {h: 14, w: 21, uom: "cm"} with a field size equal to document -- exact matching order
db.inventory.find({size: { w:21,h:14, uom: "cm"}})

// To specify query criteria for fields in embedded / nested documents, use point notation ("field.nestedField").
db.inventory.find({"size.uom": "in"})

// The following query $lt uses the less than operator () on the h embedded size field in the field:
db.inventory.find({"size.h": {$lt: 15}, "size.uom": "in", status: "D"})

4, Query documents - documents nested in an array

// -------------------------------------------------------------------------------Query documents nested in an array

// insert data
db.inventory.insertMany([
   { item: "journal", instock: [ { warehouse: "A", qty: 5 }, { warehouse: "C", qty: 15 } ] },
   { item: "notebook", instock: [ { warehouse: "C", qty: 5 } ] },
   { item: "paper", instock: [ { warehouse: "A", qty: 60 }, { warehouse: "B", qty: 15 } ] },
   { item: "planner", instock: [ { warehouse: "A", qty: 40 }, { warehouse: "B", qty: 5 } ] },
   { item: "postcard", instock: [ { warehouse: "B", qty: 15 }, { warehouse: "C", qty: 35 } ] }
])

// Select all documents whose elements in instock array match the specified documents: theoretically, this is the same as the meaning of the previous array and embedded documents. It is the most basic query - the strict matching order cannot be changed. Take a closer look and you can find the law
db.inventory.find({instock: {warehouse: "A", qty: 5}})

// Specify query criteria for the fields embedded in the document array - if you do not know the index position of the documents nested in the array, connect the names of the array fields with points (.) and the field names in the nested documents.

// The following example selects all documents 20 of embedded documents with at least one instock array containing fields with a qty value less than or equal to:
db.inventory.find({"instock.qty": {$gt: 20}})

// Use the array index to query the fields embedded in the document - array. Array subscript (this position is the object with the embedded document). Embedded variable
db.inventory.find({"instock.0.warehouse": "C"})
// Same method range lookup
db.inventory.find({"instock.0.qty": {$lt: 10}})

// The query instock array has at least one document A containing embedded documents with the field qty equal to 5 and the field warehouse equal to
db.inventory.find({instock: {$elemMatch: {qty: 5, warehouse: "A"}}})

// At least one query instock array contains a qty greater than 10 and less than or equal to 20: range: 11-20
db.inventory.find({instock: {$elemMatch: {qty: {$gt: 10, $lte: 20}}}})

// If the composite query condition on the array field does not use the $elemMatch operator, the query selects documents whose array contains any combination of elements that meet the condition.
// Query the documents that match any document nested in the instock array whose qty field is greater than 10 and any document in the array (but not necessarily the same embedded document) whose qty field is less than or equal to 20:

 // Compared with the previous sentence, this statement has one more record, item:: "planner". Previously, a single embedded object (document) can meet the conditions of 11-20. This means that as long as the value in the array, any two embedded documents can meet the conditions of greater than 10 and less than 20 respectively
db.inventory.find({"instock.qty": {$gt: 10, $lt:20}})  

// The query instock array has at least one embedded document containing the field. The qty is equal to 5. The warehouse containing the field and at least one embedded document (but not necessarily the same embedded document) is equal to A:
db.inventory.find({"instock.qty": 5, "instock.warehouse": "A"})

5, Query document - regular

The following content comes from the official website (you need to understand some of this part first, or you can read the sentence directly, and come back if you don't understand):

//Provides regular expression functionality for pattern matching strings in queries. MongoDB uses Perl compatible regular expressions (i.e. "PCRE") version 8.42 that supports UTF-8.

//To use $regex, use one of the following syntax:

 { <field>: { $regex: /pattern/, $options: '<options>' } }
 { <field>: { $regex: 'pattern', $options: '<options>' } }
 { <field>: { $regex: /pattern/<options> } }

In MongoDB, you can also use regular expression objects (i.e. / pattern /) to specify regular expressions:

{ <field>: /pattern/<options> }

The following can be used for regular expressions.
Options / description / syntax restrictions

i: Case insensitive to match case. For an example, see performing case insensitive regular expression matching.

m: For patterns containing anchors (i.e. ^ for start, $for end), strings with multiple line values are matched at the beginning or end of each line. If this option is not available, these anchors are matched at the beginning or end of the string. For an example, see multiline matching for lines beginning with a specified pattern.
This m option is not valid if the pattern does not contain an anchor or if the string value does not have a newline character (for example, \ n).

x: The "extension" function can ignore all white space characters in the pattern, $regex, unless escaped or included in the character class.
In addition, it ignores the middle characters, including the non escaped hash / pound (#) character and the next new line, so that you can include comments for complex patterns. This applies only to data characters; white space characters may never appear in special character sequences in patterns.

s: The dot character (i.e. the. Character) is allowed to match all characters including the newline character. That is, the. Character can match the newline character

TIPS: need to use s and x r e g e x And regex and regex and options syntax

Regular statement

// -------------------------------------------------------------------------------Query document - regular

// Expand from the last group of questions in query - Basic
db.inventory.find({status: "A", $or: [{qty: {$lt: 30}},{item: /^p/}]}) 

// The following effect is the same: find records beginning with n (there are too many records beginning with p, change one)
db.inventory.find({item: /^n/})
// {item: /^n /} in the statement is equivalent to {item: {$regex: "^n"} and {item: {$regex: / ^ n /}. In find, you can omit {$regex: "/ * /}, where * is the content to be written after omission
db.inventory.find({item: {$regex: "^n"}})

// $regex and / pattern / syntax

// $in expression - item starts with / ^ Not/i, /^ack/
db.inventory.find({item: { $in: [ /^Not/i, /^ack/ ]}})

// $not expression - item: does not start with p - the following results are consistent
db.inventory.find({item: {$not: /^p.*/}})
// Below (starting with MongoDB 4.0.7).
db.inventory.find({item: {$not: {$regex: "p.*"}}})
db.inventory.find({item: {$not: {$regex: /^p.*/}}})



// Implicit condition of AND field - to include a regular expression in the comma separated list of query conditions in the field, use the $regex operator. For example, find a document with lan in item (3 ways below)
// To use any x option or s option, you must use the expression of the $regex operator and the $options, that is, the first db.inventory.find({item: {$regex: /.*LaN.*/s}}) will report an error
db.inventory.find({item: {$regex: /.*LaN.*/i }})
db.inventory.find({item: {$regex: /.*LaN.*/, $options: "i"}})
db.inventory.find({item: {$regex: ".*LaN.*", $options: "si"}})

// Multiline matching with specified pattern lines - use the m option to match S lines that begin with a letter of a multiline string
// m is to match each sentence with a space / newline character. These are regarded as a new line to match
db.inventory.find({description: {$regex: /^S/, $options: "m"}})

// If the $regex pattern does not contain an anchor, the pattern matches the entire string
db.inventory.find({description: {$regex: /S/}})

6, Query document - regular reinforcement

Regular expressions are further used. This part is mainly the verification of the previous $options content

For case sensitive regular expression queries, if there is an index in the field, MongoDB matches the regular expression with the value in the index, which may be faster than collection scanning.
If the regular expression is a prefix expression, it can be further optimized
If a regular expression starts with an caret (^) or left anchor (\ A) followed by a string of simple symbols, it is a prefix expression. For example, the regular expression / ^ abc / will be optimized by matching only the values in the index beginning with abc.

// -------------------------------------------------------------------------Query document - $options validation

// insert data
db.inventory.insertMany([
{ "_id" : 100, "sku" : "abc123", "description" : "Single line description." },
{ "_id" : 101, "sku" : "abc789", "description" : "First line\nSecond line" },
{ "_id" : 102, "sku" : "xyz456", "description" : "Many spaces before     line" },
{ "_id" : 103, "sku" : "xyz789", "description" : "Multiple\nline description" }
])

// Perform LIKE matching - match all documents with sku field '% 789'
db.inventory.find({sku: {$regex: /789$/}})
// Execute LIKE matching - match all documents with sku field "abc%" - forgot ^ abc at first, pushed down and wrote out this $abc (review the old and know the new)
db.inventory.find({sku: {$regex: /^abc/}})

// Perform case insensitive regular expression matching - use the i option to perform case insensitive matching for documents with values beginning with.skuABC
db.inventory.find({sku: {$regex: /^ABC/i}})

// Multiline matching with specified pattern lines - use the m option to match S lines that begin with a letter of a multiline string
// m is to match the words separated by spaces / line breaks in each sentence as a line. Originally, it only matches the beginning and end of the string. Now it matches the head and end of each word (separated by spaces, line breaks, etc.)
db.inventory.find({description: {$regex: /^S/, $options: "m"}})

// If the $regex pattern does not contain an anchor, the pattern will match the entire string - that is, all uppercase S will match
db.inventory.find({description: {$regex: /S/}})

// Use. Dot character to match new lines - use s to allow dot characters (i.e. to match all characters including line breaks) and to perform case insensitive matching
db.inventory.find({description: {$regex: /m.*line/, $options: "si"}})
// If you do not use s, you will not be able to match [Multiple/nline description], because it is a newline character between two words
db.inventory.find({description: {$regex: /m.*line/, $options: "i"}})

// Ignore spaces in patterns - use the x option to ignore spaces and comments, represented by # and endings in matching patterns \ n   
// Theoretically (as for why, see the description of x above) [abc #category code\n123 #item number] should be [abc123] after description matching, but I will report an error [> [error] regular expression is invalid: missing)]
var pattern = "abc #category code\n123 #item number)"
db.inventory.find({sku: {$regex: pattern, $options: "x"}})

7, References

  1. MongoDB official website

Keywords: Database MongoDB

Added by gioahmad on Tue, 26 Oct 2021 18:41:00 +0300