MongoDB queries, indexes, and aggregations

Source: Internet
Author: User
Tags sorts

Initializing the MongoDB database
> Use dengswitched to DB deng> db.createcollection ("Jingdong")            #无參数 {"OK":1}> show Collectionsjingdongsystem.indexes> userdoc1= ({"user_id": 1, "name": "Cloud", "state": "Active", "actor": "User", " E-Mail ":" [email protected] "," Vm_num ": 2," time ": [{" Date ":" 2014-08-12 "," Hour ":" 10:53 PM "}]})        > userdoc2= ({" USER_ID ": 2," "Name": "Testadmin", "state": "Active", "actor": "Admin", "e-mail": "[email protected]", "Vm_num": 2, "time": [{ "Date": "2014-08-11", "Hour": "06:34 AM"}]})    > doc= ({"Name": "Peter", "position": "Teacher"}) > Db.jingdong.insert (Userdoc1) writeresult ({"ninserted": 1}) > Db.jingdong.insert (USERDOC2) writeresult ({" Ninserted ": 1}" > Db.jingdong.insert (Doc1) writeresult ({"ninserted": 1})

Query statements
Db.jingdong.find () #相当于select * from Jingdong;


Conditional operator
The conditional operators in MongoDB are: (>) greater than-\ $gt #greate (<) less than-\ $lt #low (>=) greater than or equal to-\ $gte #equal (<=) less than equals-\ $lte

Examples:
> Db.jingdong.find ({user_id:{$gt: 1}}) > Db.jingdong.find ({user_id:{$lte: 2, $GT: 1}})



#type的值双精度型-1 String-2 Object-3 array-42 binary Data-5 object ID-7 Boolean type-8 data-9 null-10 regular table -11js code-13 symbol-14 A scoped JS code-1532-bit integer-16 timestamp-1764-bit integer number -18min Key-255max Key-127db.jingdong.find ({"name": {$type: 2}}) #查找name是字符串的文档记录



Limit and Skip


MongoDB sort-sort ()

As with the sort in sqlite there are ascending and descending, in ascending with 1, descending with-1 means db.jingdong.find (). Sort ({"Time": 1})

Index-Ensureindex ()

Indexes can often greatly improve the efficiency of queries, assuming there is no index, MongoDB must scan every file in the collection and select those records that meet the criteria of the query when reading the data. Such a scan full set of query efficiency is very low, especially when processing a large amount of data. Queries can take up to dozens of seconds or even minutes. There is no doubt that the performance of the site is very deadly.

An index is a special data structure. The index is stored in a collection of data that is easy to traverse through the read. An index is a structure that sorts the values of a document or multiple documents in a database collection.

Db. Collection_name.ensureindex ({key:1|-1}) > Db.shiyanlou.ensureIndex ({"NAME": 1}) #1代表升序-1 for descending > Db.shiyanlou.ensureIndex ({"user_id": 1, "name": 1},{background:1})



The Ensureindex parameter table is as follows:
number of references type Descriptive narrative
background boolean indexing either to block other database operations, default to False
unique boolean Index established is unique, default false
name string The name of the index. If not specified. The system proactively generates
dropdups boolean When creating a unique index. Whether to delete the repeated records. Default Flase
sparse boolean The index is not enabled for field data that does not exist on the document. Default False
expireafterseconds integer Set the lifetime of the collection, in seconds
v index version version of index
weights document index weight value, range 1 to 99999
default-language string default English
Language_override String The default value is language

Polymerization-aggregate ()
Db. Collection_name.aggregate ({$match: {x:1},{limit:num}, $group: {_id: $age}})

$match: Query. Same as find; $limit: Limit the number of results displayed; $skip: ignores the number of results. $sort: Sort, $group: combines the results according to a given expression.


> db.jingdong.aggregate ([{$group: {_id: "$name", user:{$sum: "$user _id"}}])


name Descriptive narrative
$sum calculate sum
$avg calculate average
\ $min and $max calculate minimum and maximum values
$push inserting values into an array in the result document
$addToSet Insert values into an array in the resulting document, but do not create a copy
$first Get the first document data based on the sort of resource document
$last Get the last document data based on the ordering of the resource documents

Pipeline MongoDB's aggregation pipeline passes the MongoDB document to the next pipeline processing after a pipeline has finished processing.

Pipeline operations can be repeated.

Expression: Processes the input document and outputs it.

An expression is stateless. Only the documents that can be used to calculate the current aggregated pipeline cannot process other documents. Several actions that are frequently used in the aggregation framework:

$project: Changes the structure of the input document. Can be used to rename, add, or delete fields, as well as to create calculation results and nested documents. $match: Used to filter data and only output documents that match the criteria. $match a standard query operation using MONGODB. $limit: Used to limit the number of documents returned by the MongoDB aggregation pipeline. $skip: Skips the specified number of documents in the aggregation pipeline and returns the remaining documents. $unwind: Splits one of the array type fields in a document into multiple bars, each of which includes a value in the array.

$group: Groups The documents in the collection to be used for statistical results. $sort: Sorts the input documents after the output. $geoNear: Outputs an ordered document that is close to a geographic location.


> db.shiyanlou.aggregate ([{$match: {user_id:{$gt: 0, $lte: 2}}},{$group: {_id: "user", count:{$sum: 1}}]) {"_id": " User "," Count ": 2}


MongoDB queries, indexes, and aggregations

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.