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
<pre name= The conditional operators in the "code" class= "Python" >mongodb are: (>) greater than-\ $gt #greate (<) less than-\ $lt #low (>=) greater than or equal to-\ $gte #e Qual (<=) is less than or equal to-\ $lte


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


#type的值
Double Type-1 string-2 Object-3 array-42 binary Data-5 object ID-7 Boolean type-8 data-9 null-10 Regular expression -11js code-13 symbol-14 scoped JS code-1532-bit integer-16 timestamp-1764-bit integer number -18min Key-255max key-127
<pre name= "code" class= "python" ><pre name= "code" class= "Python" >db.jingdong.find ({"name": {$type: 2}}) # Find name is a string of document records



Limit and Skip


MongoDB sort-sort ()

<pre name= "code" class= "Python" > has ascending and descending order in the same way as in SQLite, where ascending is represented by 1, and descending by-1 means db.jingdong.find (). Sort ({"Time": 1})


Index-Ensureindex ()

indexes can often greatly improve the efficiency of queries, and if there is no index, MongoDB must scan every file in the collection and select those records that meet the query criteria when reading the data. This scan full set of query efficiency is very low, especially in the processing of large amounts of data, the query can take dozens of seconds or even a few minutes, no doubt the performance of the site is very deadly. indexes are special data structures that are stored in an easy-to-traverse collection of data that is a structure that sorts the values of a document or multiple documents in a database collection.

Db. Collection_name.ensureindex ({key:1|-1}) <pre name= "code" class= "Python" >> db.shiyanlou.ensureIndex ({"NAME ": 1}) #1代表升序-1 means descending
<pre name= "code" class= "Python" >> db.shiyanlou.ensureIndex ({"user_id": 1, "name": 1},{background:1})


The ensureindex parameter table is as follows:
parameter type description
background boolean indexing to not 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 automatically generates
dropdups boolean If duplicate records are deleted when a unique index is established, the default flase
sparse boolean No index is enabled for field data that does not exist for the document, default false
expireafterseconds integer Set the lifetime of the collection, in seconds
v index version The version number of the index
weights document index weight value, range 1 to 99999
default-language string default to 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: Ignore the number of results; $sort: sort; $group: Combines the results by a given expression.

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


name Description
$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. The expression is stateless and can only be used to calculate the document for the current aggregated pipeline and cannot process other documents. Several common operations in the aggregation framework:

$project: Modifies the structure of the input document. You can use it to rename, add, or delete fields, or to create calculations 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 the document into multiple bars, each containing 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.