MongoDB Study Notes (query)

Source: Internet
Author: User
Tags findone mongodb server
MongoDB learning notes (query) Postedon1. basic query: Construct the query data. Db. test. findOne () {_ id: ObjectId (4fd58ecbb9ac507e96276f1a), name: stephen, age: 35, genda: male, email: stephen@hotmail.com} -- Multi-condition query. The following example is equivalent

MongoDB learning notes (query) Posted on 1. Basic query: Construct the query data. Db. test. findOne () {"_ id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "stephen", "age": 35, "genda": "male ", "email": "stephen@hotmail.com"} -- Multi-condition query. The following example is equivalent

MongoDB Study Notes (query) Posted on

1. Basic query:
Construct the query data.
> Db. test. findOne ()
{
"_ Id": ObjectId ("4fd58ecbb9ac507e96276f1a "),
"Name": "stephen ",
"Age": 35,
"Genda": "male ",
"Email": "stephen@hotmail.com"
}

-- Multi-condition query. The following example is equivalent to the SQL 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 "}

-- Return the specified document key-value pair. The following example only returns the name and age key-value pairs.
> Db. test. find ({}, {"name": 1, "age": 1 })
{"_ Id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "stephen", "age": 35}

-- Specify the document key-value pairs that are 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": "stephen@hotmail.com "}

2. query conditions:
MongoDB provides a set of comparison operators: $ lt/$ lte/$ gt/$ gte/$ ne, which are equivalent /> = /! =.
-- The following example returns the document that meets the condition age> = 18 & age <= 40.
> 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 a condition that matches the name! = "Stephen 1"
> Db. test. find ({"name": {"$ ne": "Stephen 1 "}})
{"_ Id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "stephen", "age": 35, "genda": "male", "email ": stephen@hotmail.com "}

-- $ In is equivalent to in SQL. The following example is equivalent to in ("stephen", "stephen 1") in SQL ")
> Db. test. find ({"name": {"$ in": ["stephen", "stephen 1"]})
{"_ Id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "stephen", "age": 35, "genda": "male", "email ": stephen@hotmail.com "}

-- Unlike SQL, data in MongoDB's in list can be of different types. This situation can be used in 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 not in SQL, and is also the inverse of $ in. For example:
> Db. test. find ({"name": {"$ nin": ["Stephen 2", "Stephen 1"]})
{"_ Id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "stephen", "age": 35, "genda": "male", "email ": stephen@hotmail.com "}

-- $ Or is equivalent to or in SQL. The conditions for $ or are put in an array. Website space. Each array element represents an or condition.
-- The following example is equivalent to name = "Stephen 1" or age = 35
> Db. test. find ({"$ or": [{"name": "Stephen 1" },{ "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", "stephen 1"] }}, {"age ": 36}]})
{"_ Id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "stephen", "age": 35, "genda": "male", "email ": stephen@hotmail.com "}

-- $ Not indicates the inverse, which is equivalent to not in SQL.
> Db. test. find ({"name": {"$ not": {"$ in": ["Stephen 2", "Stephen 1"] }})
{"_ Id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "stephen", "age": 35, "genda": "male", "email ": stephen@hotmail.com "}

3. Query of null data type:
-- When querying null data, all documents whose values are null and do not contain the specified key will be retrieved.
> Db. test. find ({"x": null })
{"_ Id": ObjectId ("4fd59d30b9ac507e96276f1b"), "x": null}
{"_ Id": ObjectId ("4fd59d49b9ac507e96276f1c"), "y": 1}

-- Null must be used as an element in the array for Equality judgment, even if there is only one element in the array.
-- Then, use $ exists to determine whether the specified key exists.
> Db. test. find ({"x": {"$ in": [null], "$ exists": true }})
{"_ Id": ObjectId ("4fd59d30b9ac507e96276f1b"), "x": null}

4. Regular Expression query:
-- MongoDB uses the regular Syntax of Perl rules. For example:
> Db. test. find ()
{"_ Id": ObjectId ("4fd59ed7b9ac507e96276f1d"), "name": "stephen "}
{"_ Id": ObjectId ("4fd59edbb9ac507e96276f1e"), "name": "Stephen 1 "}
-- I indicates case-insensitive
> Db. test. find ({"name":/stephen? /I })
{"_ Id": ObjectId ("4fd59ed7b9ac507e96276f1d"), "name": "stephen "}
{"_ Id": ObjectId ("4fd59edbb9ac507e96276f1e"), "name": "Stephen 1 "}

5. query array data:
-- Search based on arrays.
> 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"]}
-- Retrieve the case where the array needs to contain multiple elements. $ all is used here. In the following example, the array must contain both apple and banana, but their order does not 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 indicates exact match, that is, the retrieved document. The array data in the fruit value must exactly match the query condition, that is, there must be no more or less, the order must also be consistent.
> Db. test. find ({"fruit": ["apple", "banana", "peach"]})
{"_ Id": ObjectId ("4fd5a177b9ac507e96276f1f"), "fruit": ["apple", "banana", peach "]}
-- The following example matches the value of the specified subscript element in the array. The starting subscript of the array is 0.
> Db. test. find ({"fruit.2": "peach "})
{"_ Id": ObjectId ("4fd5a177b9ac507e96276f1f"), "fruit": ["apple", "banana", peach "]}
-- The length of the array can be obtained through $ size, but $ size cannot be used together with comparison operators.
> 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"]}
-- To retrieve results with size> n, you cannot use $ size directly. You can only add an additional key to indicate the element data in the data. When operating on the elements in the data, the value of the size key needs to be updated at the same time.
-- 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}
-- Each time a new element is added, the atomic auto-increment size is required.
> 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}
-- Partial data in the array is returned through $ slice. "$ Slice": 2 indicates 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"]}
-- Partial data in the array is returned through $ slice. "$ Slice":-2 indicates 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], which indicates that one element is obtained from the second element 2. If the number is greater than the number of elements after 2, all the subsequent data is obtained.
> Db. test. find ({}, {"fruit": {"$ slice": [2, 1]}, "size": 0 })
{"_ Id": ObjectId ("4fd5a18cb9ac507e96276f20"), "fruit": ["orange"]}
{"_ Id": ObjectId ("4fd5a1f0b9ac507e96276f21"), "fruit": ["apple"]}

6. embedded document query:
-- Construct test data for the following example.
> Db. test. find ()
{"_ Id": ObjectId ("4fd5ada3b9ac507e96276f22"), "name": {"first": "Joe", "last": "He"}, "age ": 45}
-- When the embedded document is an array, the $ elemMatch operator is required to help locate the matching of an element. Otherwise, all the embedded files will be matched.
-- This means that all elements must be listed as query conditions during retrieval.
> 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. cursor:
The database uses a cursor to return the execution result of find (). The client can effectively control the cursor, for example: limit the number of result sets, skip partial results, and sort any direction based on any key.
The following example is used to prepare test data.
> Db. testtable. remove ()
> For (I = 0; I <10; ++ I ){
... Db. testtable. insert ({x: I })
...}
We can use the hasNext () method provided by cursor to determine whether there is any unread data, and then use the next () method to read the next document in the result set. For example:
> Var c = db. testtable. find ()
> While (c. hasNext ()){
... Print (c. next (). x)
...}
0
1
2
3
4
5
6
7
8
9
When you call find (), the shell does not query the database immediately, but sends the query only when the query results are actually required. Therefore, you can add additional options to the query before execution. Almost all the cursor Methods return their own, so you can chain and combine the cursor methods 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 time, the query is not executed, and all these functions are constructing the query. When the following statement is executed, the query will be actually executed on the U.S. server,
> C. hasNext ()
The query is sent to the server. The MongoDB server returns a batch of data each time. When this batch is completely iterated, it reads the next batch of data from the server until all the data required for the query result is iterated.

For the above example, limit (1) indicates that the output result is only one space in Hong Kong. If it is smaller than 1, no output is made. That is, the limit (n) function limits the maximum output result. Skip (4) indicates that the first four documents in the query results are skipped. If the result is smaller than 4, no documents are returned. Sort ({"x": 1}) is used to set sorting conditions, that is, sort by the x key in ascending order (1). If you need to sort in descending order, you can change it: sort ({"x":-1 }). Sort can also support multi-key sorting, for example, sort ({username: 1, age:-1}) first sort by username in ascending order. If username values are the same, sort by age in descending order. It should be pointed out that if there are too many documents with skip addresses, it will cause performance problems.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.