MongoDB Tutorial Examples of query operations _mongodb

Source: Internet
Author: User
Tags comments findone mongodb mongodb server mongodb tutorial

1. Basic query:

Constructs query data.

Copy Code code as follows:

> 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 WHERE name = "Stephen" and age = 35 of the SQL statement
> Db.test.find ({"Name": "Stephen", "Age": 35})
{"_id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "Stephen", "Age": "Genda": "Male", "email": "Stephen@hotma Il.com "}

--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 a document key value pair that is not returned. The following example returns all key-value pairs except name.
> Db.test.find ({}, {"name": 0})
{"_id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "Age": "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 </<=/>/>=/!=.

Copy Code code as follows:

--The following example returns a document that matches the condition age >= && age <= 40.
> Db.test.find ({"Age": {"$gte": "$lte": 40}})
{"_id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "Stephen", "Age": "Genda": "Male", "email": "Stephen@hotmai L.com "}

--The following example returns a condition that conforms to the name!= "Stephen1"
> Db.test.find ({"name": {"$ne": "Stephen1"}})
{"_id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "Stephen", "Age": "Genda": "Male", "email": "Stephen@hotmai L.com "}

--$in equivalent to in in SQL, the following example is equivalent to in ("Stephen", "Stephen1") in SQL
> Db.test.find ({"name": {"$in": ["Stephen", "Stephen1"]}})
{"_id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "Stephen", "Age": "Genda": "Male", "email": "Stephen@hotmai L.com "}

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.
> Db.test.find ({"name": {"$in": ["Stephen", 123]}})
{"_id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "Stephen", "Age": "Genda": "Male", "email": "Stephen@hotmai L.com "}

-$nin is equivalent to not in in SQL and is also $in. Such as:
> Db.test.find ({"name": {"$nin": ["Stephen2", "Stephen1"]}})
{"_id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "Stephen", "Age": "Genda": "Male", "email": "Stephen@hotmai L.com "}

--$or equal to or in SQL, $or the condition to be placed in an array in which each array element represents a condition of OR.
--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": "Genda": "Male", "email": "Stephen@hotmai L.com "}

--The following example shows how to mix $or and $in.
> Db.test.find ({"$or": [{"name": {"$in": ["Stephen", "Stephen1"]}}, {"Age": 36}]})
{"_id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "Stephen", "Age": "Genda": "Male", "email": "Stephen@hotmai L.com "}

--$not represents reverse, equivalent to not in SQL.
> Db.test.find ({"name": {"$not": {"$in": ["Stephen2", "Stephen1"]}})
{"_id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "Stephen", "Age": "Genda": "Male", "email": "Stephen@hotmai L.com "}

3. Query for NULL data type:

Copy Code code as follows:

-When a query with a value of NULL data is made, 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 make equality judgments about NULL as an element in the array, even if there is only one element in the array.
-Then there is the $exists to determine whether the specified key exists.
> Db.test.find ({"x": {"$in": [null], $exists: true}})
{"_id": ObjectId ("4FD59D30B9AC507E96276F1B"), "X": null}

4. Regular enquiries:
Copy Code code as follows:

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 for ignoring case
> Db.test.find ({"Name":/stephen?/i})
{"_id": ObjectId ("4fd59ed7b9ac507e96276f1d"), "name": "Stephen"}
{"_id": ObjectId ("4fd59edbb9ac507e96276f1e"), "name": "Stephen1"}

5. Array data query:
Copy Code code as follows:

--based on an array of 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 are retrieved.
> db.test.find ({"Fruit": "Banana"})
{"_id": ObjectId ("4fd5a177b9ac507e96276f1f"), "fruit": ["apple", "banana", "Peach"]}
{"_id": ObjectId ("4fd5a1f0b9ac507e96276f21"), "fruit": ["Cherry", "banana", "Apple"]}
--Retrieves a case where multiple elements are needed in an array, using $all. In the following example, both Apple and banana must be included in the array, 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 an exact match, that is, the retrieved document, the array data in the fruit value must exactly match the query criteria, that is, not much, not less, and the order must 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 an array. The starting subscript for 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 by $size, but $size cannot be used in conjunction 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"]}
-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 when manipulating elements in the data, you need to update the value of the size key at the same time.
--Construct the data for the subsequent experiment.
> 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 size is increased once.
> 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}
--Returns some of the data in the array via $slice. "$slice": 2 represents the first two elements in an array.
> db.test.find ({},{"fruit": {"$slice": 2}, "Size": 0})
{"_id": ObjectId ("4fd5a18cb9ac507e96276f20"), "fruit": ["apple", "Kumquat"]}
{"_id": ObjectId ("4fd5a1f0b9ac507e96276f21"), "fruit": ["Cherry", "Banana"]}
--Returns some of the data in the array via $slice. "$slice":-2 represents the latter 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 that 1 are started from the second 2 element, and if the number of elements after the quantity is greater than 2 is fetched, then all subsequent data is taken.
> db.test.find ({},{"fruit": {"$slice": [2,1]}, "Size": 0})
{"_id": ObjectId ("4fd5a18cb9ac507e96276f20"), "fruit": ["Orange"]}
{"_id": ObjectId ("4fd5a1f0b9ac507e96276f21"), "fruit": ["Apple"]}

6. Inline Document query:
Copy Code code as follows:

-Constructs test data for the following example.
> Db.test.find ()
{"_id": ObjectId ("4fd5ada3b9ac507e96276f22"), "name": {"a": "Joe", "last": "Him"}, "Age": 45}
--When an embedded document is an array, the $elemmatch operator is required to help locate an element match, otherwise the embedded file will make all the matches.
-that is, all elements need to be listed as query criteria for 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", "SC Ore ': 6}]}

7. Cursors:

The database uses Grand to return the results of find (), and the client can control the cursor effectively, 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.

Copy Code code as follows:

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

We can use the Hasnext () method provided by cursor to determine if there is still unread data and then read the next document in the result set through the next () method. Such as:
Copy Code code as follows:

> 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 waits until the result is actually started, so that you can append additional options to the query before executing. Almost all cursor methods return themselves, so you can combine the methods of a cursor as follows. Such as:
Copy Code code as follows:

> 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 constructs the query, when executes the following statement, the query will be actually executed,
Copy Code code as follows:

> C.hasnext ()

The query is sent to the server, and the MongoDB server returns a batch of data each time, then reads the next batch of data from the server when the batch is fully iterated until the data required by the query results is all iterated.

For the above example, limit (1) indicates that the output is only one, and if it is less than 1, it does not output, that is, the limit (n) function qualifies the maximum output. Skip (4) skips the first 4 documents in the query result and returns no documents if the result is less than 4. Sort ({"X": 1}) is used to set the sort criteria, that is, to sort by the X key in ascending order (1), if a descending sort is required to: sort ({"X":-1}). Sort can also support multiple-key sorting, such as: sort ({username:1, age:-1}) that is sorted in ascending order by username, if the username values are the same, and then sorted in descending order with the age key. It should be noted here that if you skip too many documents, you 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.