Examples of query operations in the MongoDB tutorial

  • 2020-05-27 07:28:57
  • OfStack

1. Basic inquiry:

Construct query data.


    > db.test.findOne()
    {
         "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"),
         "name" : "stephen",
         "age" : 35,
         "genda" : "male",
         "email" : "stephen@hotmail.com"
    }
 
    -- Multi-conditional queries. The following example is equivalent to SQL The statement where name = "stephen" and age = 35
    > db.test.find({"name":"stephen","age":35})
    { "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35, "genda" : "male", "email" : "stephen@hotmail.com" }
 
    -- Returns the specified document key-value pair. The following example will simply return name and age Key/value pair.
    > db.test.find({}, {"name":1,"age":1})
   { "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35 }       -- Specifies a document key-value pair that is not returned. The following example returns the division name All key-value pairs except.
    > db.test.find({}, {"name":0})
    { "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "age" : 35, "genda" : "male", "email" : "stephen@hotmail.com" }
 

2. Query conditions:

MongoDB provides a set of comparison operators: $lt/$lte/$gt/$gte/$ne, which in turn is equivalent to < / < =/ > / > = /! =.


    -- The following example returns eligibility age >= 18 && age <= 40 The document.
    > db.test.find({"age":{"$gte":18, "$lte":40}})
    { "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35,"genda" : "male", "email" : "stephen@hotmail.com" }
 
    -- The following example returns that the condition is met name != "stephen1"
    > db.test.find({"name":{"$ne":"stephen1"}})
    { "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35,"genda" : "male", "email" : "stephen@hotmail.com" }
 
    --$in Is equivalent to SQL In the in , the following example is equivalent to SQL In the in ("stephen","stephen1")
    > db.test.find({"name":{"$in":["stephen","stephen1"]}})
    { "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35,"genda" : "male", "email" : "stephen@hotmail.com" } 
 
    -- and SQL The difference is, MongoDB the in list The data in can be of different types. This can be used for different types of alias scenarios.
    > db.test.find({"name":{"$in":["stephen",123]}})
    { "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35,"genda" : "male", "email" : "stephen@hotmail.com" }
 
    --$nin Is equivalent to SQL In the not in At the same time $in The invert. Such as:
    > db.test.find({"name":{"$nin":["stephen2","stephen1"]}})
    { "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35,"genda" : "male", "email" : "stephen@hotmail.com" }
 
    --$or Is equivalent to SQL In the or . $or The conditions are put in 1 Each element of an array is represented or the 1 A condition.
    -- The following example is equivalent to name = "stephen1" or age = 35
    > db.test.find({"$or": [{"name":"stephen1"}, {"age":35}]})
    { "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35,"genda" : "male", "email" : "stephen@hotmail.com" }
 
    -- The following example demonstrates how to mix $or and $in .
    > db.test.find({"$or": [{"name":{"$in":["stephen","stephen1"]}}, {"age":36}]})
    { "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35,"genda" : "male", "email" : "stephen@hotmail.com" }
 
    --$not It's going to be the same thing SQL In the not .
    > db.test.find({"name": {"$not": {"$in":["stephen2","stephen1"]}}})
    { "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35,"genda" : "male", "email" : "stephen@hotmail.com" }

3. Query of null data type:


    -- The ongoing value is null When the data is queried, all values are null , and documents that do not contain the specified key are retrieved.
    > db.test.find({"x":null})
    { "_id" : ObjectId("4fd59d30b9ac507e96276f1b"), "x" : null }
    { "_id" : ObjectId("4fd59d49b9ac507e96276f1c"), "y" : 1 }
 
    -- You need to null As an array 1 Two elements for equality, even if the array has only one 1 An element.
    -- And then through $exists Determines whether the specified key exists.
    > db.test.find({"x": {"$in": [null], "$exists":true}})
    { "_id" : ObjectId("4fd59d30b9ac507e96276f1b"), "x" : null }
 

4. Regular query:

    --MongoDB The use of the Perl Regular syntax for rules. Such as:
    > db.test.find()
    { "_id" : ObjectId("4fd59ed7b9ac507e96276f1d"), "name" : "stephen" }
    { "_id" : ObjectId("4fd59edbb9ac507e96276f1e"), "name" : "stephen1" }
    --i Ignore case
    > db.test.find({"name":/stephen?/i})
    { "_id" : ObjectId("4fd59ed7b9ac507e96276f1d"), "name" : "stephen" }
    { "_id" : ObjectId("4fd59edbb9ac507e96276f1e"), "name" : "stephen1" }
 

5. Array data query:

    -- Array-based lookup.
    > db.test.find()
    { "_id" : ObjectId("4fd5a177b9ac507e96276f1f"), "fruit" : [ "apple", "banana", "peach" ] }
    { "_id" : ObjectId("4fd5a18cb9ac507e96276f20"), "fruit" : [ "apple", "kumquat","orange" ] }
    { "_id" : ObjectId("4fd5a1f0b9ac507e96276f21"), "fruit" : [ "cherry", "banana","apple" ] }
    -- Everything in the array banana The document will be retrieved.
    > db.test.find({"fruit":"banana"})
    { "_id" : ObjectId("4fd5a177b9ac507e96276f1f"), "fruit" : [ "apple", "banana", "peach" ] }
    { "_id" : ObjectId("4fd5a1f0b9ac507e96276f21"), "fruit" : [ "cherry", "banana","apple" ] }
    -- Retrieve the case where an array needs to contain more than one element, used here $all . In the following example, the array must contain both apple and banana But their order doesn't matter.
    > db.test.find({"fruit": {"$all": ["banana","apple"]}})
    { "_id" : ObjectId("4fd5a177b9ac507e96276f1f"), "fruit" : [ "apple", "banana", "peach" ] }
    { "_id" : ObjectId("4fd5a1f0b9ac507e96276f21"), "fruit" : [ "cherry", "banana", "apple" ] }
    -- The following example shows an exact match, that is, a retrieved document, fruit The array data in the values must match the query criteria exactly, no more, no less, and the order must be maintained 1 Cause.
    > db.test.find({"fruit":["apple","banana","peach"]})
    { "_id" : ObjectId("4fd5a177b9ac507e96276f1f"), "fruit" : [ "apple", "banana", peach" ] }
    -- The following example matches the value of the subscript element specified in the array. The starting index of the array is 0 .
    > db.test.find({"fruit.2":"peach"})
    { "_id" : ObjectId("4fd5a177b9ac507e96276f1f"), "fruit" : [ "apple", "banana", peach" ] }
    -- Can be achieved by $size Get the length of the array, but $size Cannot be used in conjunction with the comparison operator.
    > db.test.find({"fruit": {$size : 3}})
    { "_id" : ObjectId("4fd5a177b9ac507e96276f1f"), "fruit" : [ "apple", "banana", "peach" ] }
    { "_id" : ObjectId("4fd5a18cb9ac507e96276f20"), "fruit" : [ "apple", "kumquat","orange" ] }
    { "_id" : ObjectId("4fd5a1f0b9ac507e96276f21"), "fruit" : [ "cherry", "banana","apple" ] }
    -- If you need to retrieve size > n The results cannot be used directly $size , can only be added 1 Four additional keys represent elements in the data that need to be updated at the same time as the elements in the data are manipulated size The value of the key.
    -- Construct data for subsequent experiments.
    > db.test.update({}, {"$set": {"size":3}},false,true)
    > db.test.find()
    { "_id" : ObjectId("4fd5a18cb9ac507e96276f20"), "fruit" : [ "apple", "kumquat", "orange" ], "size" : 3 }
    { "_id" : ObjectId("4fd5a1f0b9ac507e96276f21"), "fruit" : [ "cherry", "banana", "apple" ], "size" : 3 }
    -- Every time I add 1 Each new element has to be atomic size1 Times.
    > test.update({},{"$push": {"fruit":"strawberry"},"$inc":{"size":1}},false,true)
    > db.test.find()
    { "_id" : ObjectId("4fd5a18cb9ac507e96276f20"), "fruit" : [ "apple", "kumquat", "orange", "strawberry" ], "size" : 4 }
    { "_id" : ObjectId("4fd5a1f0b9ac507e96276f21"), "fruit" : [ "cherry", "banana", "apple", "strawberry" ], "size" : 4 }
    -- through $slice Returns part of the data in the array. "$slice":2 Represents the first two elements in the array.
    > db.test.find({},{"fruit": {"$slice":2}, "size":0})
    { "_id" : ObjectId("4fd5a18cb9ac507e96276f20"), "fruit" : [ "apple", "kumquat" ]}
    { "_id" : ObjectId("4fd5a1f0b9ac507e96276f21"), "fruit" : [ "cherry", "banana" ]}
    -- through $slice Returns part of the data in the array. "$slice":-2 Represents the last two elements in the array.
    > db.test.find({},{"fruit": {"$slice":-2}, "size":0})
    { "_id" : ObjectId("4fd5a18cb9ac507e96276f20"), "fruit" : [ "orange", "strawberry" ] }
    { "_id" : ObjectId("4fd5a1f0b9ac507e96276f21"), "fruit" : [ "apple", "strawberry" ] }
    --$slice : [2,1] , from the first 2 a 2 Element start 1 If the number of fetches is greater than 2 The number of elements in the end, then take all the data in the end.
    > db.test.find({},{"fruit": {"$slice":[2,1]}, "size":0})
    { "_id" : ObjectId("4fd5a18cb9ac507e96276f20"), "fruit" : [ "orange" ] }
    { "_id" : ObjectId("4fd5a1f0b9ac507e96276f21"), "fruit" : [ "apple" ] }
 

6. Inline document query:

    -- Construct the test data for the following examples.
    > db.test.find()
    { "_id" : ObjectId("4fd5ada3b9ac507e96276f22"), "name" : { "first" : "Joe", "last" : "He" }, "age" : 45 }
    -- When embedded documents are arrays, you need to $elemMatch Operator to help locate something 1 Element matching, otherwise the embedded file will be all matched.
    -- That is, all the elements need to be listed as a query condition.
    > db.test.findOne()
    {
         "_id" : ObjectId("4fd5af76b9ac507e96276f23"),
         "comments" : [
                 {
                         "author" : "joe",
                         "score" : 3
                 },
                 {
                         "author" : "mary",
                         "score" : 6
                 }
         ]
    }
    > db.test.find({"comments": {"$elemMatch": {"author":"joe","score":{"$gte":3}}}}
    { "_id" : ObjectId("4fd5af76b9ac507e96276f23"), "comments" : [ { "author" : "joe", "score" : 3 }, { "author" : "mary", "score" : 6 } ] }
 

7. The cursor:

The database USES the cursor to return the find() execution results, and the client can effectively control the cursor, such as limiting the number of result sets, skipping partial results, sorting in any direction based on any key, and so on.
The following example will be used to prepare the test data.


    > db.testtable.remove()
    > for (i = 0; i < 10; ++i) {
    ... db.testtable.insert({x:i})
    ... }

We can determine if there is any unread data through the hasNext() method provided by cursor, and then read the next document in the result set through the next() method. Such as:

    > var c = db.testtable.find()
    > while (c.hasNext()) {
    ... print(c.next().x)
    ... }
    0
    1
    2
    3
    4
    5
    6
    7
    8
    9
 

When find() is called, shell does not query the database immediately, but instead waits until the actual request for results begins, so that additional options can be added to the query before execution. Almost all cursor methods return themselves, so you can chain up cursor methods as follows. Such as:

    > var c1 = db.testtable.find().sort({"x":1}).limit(1).skip(4);
    > var c2 = db.testtable.find().limit(1).sort({"x":1}).skip(4);
    > var c3 = db.testtable.find().skip(4).limit(1).sort({"x":1});
 

At this point, the query is not executed, all of these functions are constructing the query, and when the following statement is executed, the query will actually be executed,

    > c.hasNext()
 

The query is sent to the server, and MongoDB server will return 1 batch of data each time. After the whole batch is iterated, the next batch of data will be read from the server, until all the data required by the query result are iterated.

For the above example, limit(1) means that the output is only 1, and if it is less than 1, no output, that is, the limit(n) function qualifies the maximum output. skip(4) means that the first four documents in the query result are skipped, and no documents are returned if the result is less than 4. sort({"x":1}) is used to set sort conditions, that is, sort in ascending order (1) according to x key. If you want to sort in descending order, you can change it to: sort({"x":-1}). sort can also support multi-key sorting, such as: sort({username:1, age:-1}), that is, first sort in ascending order by username, and then sort in descending order by age if username has the same value. It should be noted here that if skip has too many documents, it will cause performance problems.


Related articles: