MongoDB basic Commands

Source: Internet
Author: User
Tags findone mongodb server

This article turns from http://www.cnblogs.com/stephen-liu74/archive/2012/08/03/2553803.html

1. Basic Enquiry:
Constructs the query data.
> Db.test.findOne ()
{
"_id": ObjectId ("4fd58ecbb9ac507e96276f1a"),
"Name": "Stephen",
"Age": 35,
"Genda": "Male",
"Email": "[email protected]"
}

--Multi-criteria query. The following example is equivalent to the where name of the SQL statement = "Stephen" and age =
> Db.test.find ({"Name": "Stephen", "Age": 35})
{"_id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "Stephen", "Age": +, "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 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": "[email protected]" }

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 a document that meets the conditions of age >= && age <= 40.
> Db.test.find ({"Age": {"$gte": "$lte": 40}})
{"_id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "Stephen", "Age": +, "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": +, "Genda": "Male", "email": "[email protected]" }

--$in is equivalent to in in SQL, the following example is equivalent to the in ("Stephen", "Stephen1") of SQL
> Db.test.find ({"name": {"$in": ["Stephen", "Stephen1"]}})
{"_id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "Stephen", "Age": +, "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.
> Db.test.find ({"name": {"$in": ["Stephen", 123]}})
{"_id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "Stephen", "Age": +, "Genda": "Male", "email": "[email protected]" }

--The $nin is equivalent to the not in of SQL and is also the inverse of $in. such as:
> Db.test.find ({"name": {"$nin": ["Stephen2", "Stephen1"]}})
{"_id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "Stephen", "Age": +, "Genda": "Male", "email": "[email protected]" }

--$or is equivalent to or in SQL, $or the conditions to be placed into an array, each array element represents a condition of OR.
--The following example is equivalent to name = "Stephen1" or age =
> Db.test.find ({"$or": [{"Name": "Stephen1"}, {"Age": 35}]})
{"_id": ObjectId ("4fd58ecbb9ac507e96276f1a"), "name": "Stephen", "Age": +, "Genda": "Male", "email": "[email protected]" }

--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": "[email protected]" }

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

3. Query for the null data type:
--When a query with 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 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 to determine whether the specified key exists.
> Db.test.find ({"x": {"$in": [null], "$exists": True}})
{"_id": ObjectId ("4FD59D30B9AC507E96276F1B"), "X": null}

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

5. 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"]}
--Retrieve the case where multiple elements are required in the array, using $all. In the following example, both Apple and banana must be included in the array.but their order is irrelevant.
> 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, i.e. no more, no 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 the array. The starting subscript for an 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 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 results of size > N, you cannot use $size directly, only add an extra key to represent the element data in the data, and when manipulating the elements in the data, you need to update the value of the size key 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 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"], "Size": 4}
{"_id": ObjectId ("4fd5a1f0b9ac507e96276f21"), "fruit": ["Cherry", "banana", "apple", "Strawberry"], "Size": 4}
--Returns some of the data in the array by $slice. "$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"]}
--Returns some of the data in the array by $slice. "$slice":-2 represents the second 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 1 is taken from the second 2 element, and all subsequent data is taken if the number of elements following the quantity greater than 2 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:
--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, the $elemmatch operator is required to help locate an element match, otherwise the embedded file will be fully matched.
--that is, all elements need to be listed as query criteria.
> 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 cursors to return the execution results of find (), which can be effectively controlled by the client, such as the number of qualifying result sets, the skipping of partial results, the ordering of any direction based on any key.
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 determine if there are any unread data through the cursor's Hasnext () method, 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 you call find (), the shell does not immediately query the database, but instead 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. 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 is actually executed,
> C.hasnext ()
When the query is sent to the server, 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.

MongoDB basic Commands

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.