Original address
MongoDB Learning Notes (query)
Basic query:
Constructs the query data.
> db.test.findOne(){ "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35, "genda" : "male", "email" : "[email protected]"}
Multi-criteria queries. The following example is equivalent to the where name of the SQL statement = "Stephen" and age = 35
> db.test.find({"name":"stephen","age":35}){ "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35, "genda" : "male", "email" : "[email protected]" }
Returns the specified document key-value pair. The following example will simply return the name and age key-value pairs.
> db.test.find({}, {"name":1,"age":1}) { "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35 }
Specifies that a document key-value pair is not returned. The following example returns all key-value pairs except name.
> db.test.find({}, {"name":0}){ "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "age" : 35, "genda" : "male", "email" : "[email protected]" }
Query criteria
MongoDB provides a set of comparison operators: $lt/$lte/$gt/$gte/$ne
, in turn, is equivalent to </<=/>/>=/!=
.
- The following example returns a document that meets the conditions of age >= && age <= 40.
> db.test.find({"age":{"$gte":18, "$lte":40}}){ "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35,"genda" : "male", "email" : "[email protected]" }
The following example returns a condition that matches the name! = "Stephen1"
> db.test.find({"name":{"$ne":"stephen1"}}){ "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35,"genda" : "male", "email" : "[email protected]" }
$in
Equivalent to in in SQL, the following example is equivalent to in SQL ("Stephen", "Stephen1")
> db.test.find({"name":{"$in":["stephen","stephen1"]}}){ "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35,"genda" : "male", "email" : "[email protected]" }
Unlike SQL, the data in the MongoDB in list can be of different types. This situation can be used for different types of alias scenarios.
$nin
is equivalent to the not in of SQL and is also $in
an inverse. Such as:
> db.test.find({"name":{"$nin":["stephen2","stephen1"]}}){ "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35,"genda" : "male", "email" : "[email protected]" }
$or
Equivalent to or in SQL, the $or
condition being targeted is put into an array, and each array element represents a condition of OR.
The following example is equivalent to name = "Stephen1" or age = 35
The following example shows how to mix and use the $or
$in
.
$not
Represents the inverse, which is equivalent to not in SQL.
> db.test.find({"name": {"$not": {"$in":["stephen2","stephen1"]}}}){ "_id" : ObjectId("4fd58ecbb9ac507e96276f1a"), "name" : "stephen", "age" : 35,"genda" : "male", "email" : "[email protected]" }
Query for a null data type
When you make a query that has a value of NULL data, 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 judge the equality of NULL as an element in the array, even if there is only one element in the array. Then there is the $exists
determination of whether the specified key exists.
> db.test.find({"x": {"$in": [null], "$exists":true}}){ "_id" : ObjectId("4fd59d30b9ac507e96276f1b"), "x" : null }
Regular queries
The regular syntax for Perl rules is used in MongoDB. Such as:
> db.test.find(){ "_id" : ObjectId("4fd59ed7b9ac507e96276f1d"), "name" : "stephen" }{ "_id" : ObjectId("4fd59edbb9ac507e96276f1e"), "name" : "stephen1" }
-I indicates ignoring case
Array data query
Array-based lookups.
> db.test.find(){ "_id" : ObjectId("4fd5a177b9ac507e96276f1f"), "fruit" : [ "apple", "banana", "peach" ] }{ "_id" : ObjectId("4fd5a18cb9ac507e96276f20"), "fruit" : [ "apple", "kumquat","orange" ] }{ "_id" : ObjectId("4fd5a1f0b9ac507e96276f21"), "fruit" : [ "cherry", "banana","apple" ] }
All documents containing banana in the array will be retrieved.
> db.test.find({"fruit":"banana"}){ "_id" : ObjectId("4fd5a177b9ac507e96276f1f"), "fruit" : [ "apple", "banana", "peach" ] }{ "_id" : ObjectId("4fd5a1f0b9ac507e96276f21"), "fruit" : [ "cherry", "banana","apple" ] }
Retrieves the case where multiple elements need to be contained in an array, which is used here $all
. In the following example, both Apple and banana must be included in the array, but their order does not matter.
The following example shows an exact match, that is, the retrieved document, the array data in the fruit value must match the query criteria exactly, that is, neither more nor less, and the order must be consistent.
The following example matches the value of the specified subscript element in the array. The starting subscript for an array is 0.
You can $size
do this by getting the length of the array, but not in conjunction with the $size
comparison operator.
> Db.test.find ({"fruit": {$size: 3}}) {"_id": ObjectId ("4fd5a177b9ac507e96276f1f"), "fruit": ["Apple", " Banana "," peach "]} {" _id ": ObjectId (" 4fd5a18cb9ac507e96276f20 ")," fruit ": [" apple "," kumquat "," Orange "]} {" _id ": O Bjectid ("4fd5a1f0b9ac507e96276f21"), "fruit": ["Cherry", "banana", "Apple"]}
- If you need to retrieve the result of size > N, you cannot use
$size
directly, you can only add an extra key to represent the element data in the data, and you need to update the value of the size key at the same time when you manipulate the elements in the data.
-
Constructs the 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 (" 4fd5a1f0b9ac507e96 276f21 ")," fruit ": [" Cherry "," banana "," apple "]," Size ": 3}
-
Each time you add a new element, you have to atomically increment the size one time.
> test.update ({},{"$push": {"fruit": "Strawberry"}, "$inc": {"size": 1}},false,true) > Db.test.find () {"_id": ObjectId ("4fd5a18cb9ac507e96276f20"), "fruit": ["apple", "kumquat", "orange", "Strawberry"], "s Ize ": 4} {" _id ": ObjectId (" 4fd5a1f0b9ac507e96276f21 ")," fruit ": [" Cherry "," banana "," apple "," Strawberry "]," size " : 4}
-
Returns some of the data in the array via $slice
. $slice: 2
represents the first two elements in the array.
By $slice
returning some of the data in the array. "$slice":-2
represents the first two elements in an array.
> db.test.find({},{"fruit": {"$slice":-2}, "size":0}){ "_id" : ObjectId("4fd5a18cb9ac507e96276f20"), "fruit" : [ "orange", "strawberry" ] }{ "_id" : ObjectId("4fd5a1f0b9ac507e96276f21"), "fruit" : [ "apple", "strawberry" ] }
- $slice
: [2,1], which means starting from the second 2 element to take 1, if the number is greater than 2 after the number of elements, then take all the data behind.
> db.test.find({},{"fruit": {"$slice":[2,1]}, "size":0}){ "_id" : ObjectId("4fd5a18cb9ac507e96276f20"), "fruit" : [ "orange" ] }{ "_id" : ObjectId("4fd5a1f0b9ac507e96276f21"), "fruit" : [ "apple" ] }
Inline document Query
Constructs the test data for the following example.
> db.test.find(){ "_id" : ObjectId("4fd5ada3b9ac507e96276f22"), "name" : { "first" : "Joe", "last" : "He" }, "age" : 45 }
- When an embedded document is an array, an operator is required
$elemMatch
to help locate an element match, otherwise the embedded file will be matched in its entirety.
That is, all elements need to be listed as criteria for the query to be retrieved.
> 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 } ] }
Cursor
The
-
Database uses cursors to return the execution results of find (), which can be effectively controlled by the client, such as the number of qualifying 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 < ten; ++i) {... db.testtable.insert ({x:i}) ...}
We can use the Hasnext () method provided by the cursor to determine if there is any data that is not read, 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) ...}
When you call find (), the shell does not query the database immediately, but waits for the query to be sent when the result is actually started, so that additional options can be attached to the query before execution. Almost all cursor methods return themselves, so you can combine the method chaining of cursors as follows. For example:
> 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 is actually executed,
> C.hasnext ()
The Query is sent to the server, and the MongoDB server returns a batch of data each time, and when the batch is fully iterated, the next batch of data is read from the server until the data required by the query result is fully iterated.
For the example above, the limit (1) indicates that the output is only one, and if it is less than 1, it is not output, that is, the limit (n) function qualifies the maximum output. Skip (4) means that the first 4 documents in the query result are skipped, and if the result is less than 4, no document is returned. The sort ({"X": 1}) is used to set the sorting criteria, which is to sort by the X key in ascending (1) order, and if a descending order is required, it can be changed to: sort ({"X":-1}). Sort can also support multi-key sorting, such as sort ({username:1, age:-1}) that is sorted in ascending order by username, and if the username values are the same, then sorted in descending order by the age key. It should be noted here that if you skip too many documents, you will cause performance problems.
"Turn" MongoDB Learning Notes (query)