MongoDB query, index, and aggregation

Source: Internet
Author: User
Tags mongodb query

MongoDB query, index, and aggregation
Initialize the mongodb Database

> Use dengswitched to db deng> db. createCollection ("jingdong") # No parameter {"OK": 1}> show collectionsjingdongsystem. indexes> userdoc1 = ({"user_id": 1, "name": "cloud", "state": "active", "actor": "user ", "e-mail": "test@qq.com", "VM_num": 2, "time": [{"date": "", "hour ": "53 53 PM"}]})> userdoc2 = ({"user_id": 2, "name": "testadmin", "state": "active", "actor ": "admin", "e-mail": "test@qq.com", "VM_num": 2, "time": [{"date": "", "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 statement
Db. jingdong. find () # equivalent to select * from jingdong;
Conditional Operators
 
The conditional operators in mongodb include: (>) greater than-\ $ gt # greate (<) less than-\ $ lt # low (> =) greater than or equal to-\ $ gte # equal (<=) less than or equal to-\ $ lte
Example: 

> db.jingdong.find({user_id:{$gt:1}})> db.jingdong.find({user_id:{$lte:2,$gt:1}})
# Type value
Double precision-1 string-2 object-3 array-4 binary data-5 Object ID-7 boolean type-8 Data-9 null-10 regular expression-11JS code-13 symbol- 14 JavaScript code with scope-1532-bit integer-16 timestamp-1764-127-18 Min key-255Max key-
 
 
Db. jingdong. find ({"name": {$ type: 2}) # search for document records whose name is a string

Limit and skip

Read a specified number of data records-limitdb. shiyanlou. find (). limit (1) # Read a record. By default, it is the first data record to be read and skipped-skipdb. shiyanlou. find (). limit (1 ). skip (1)
MongoDB sorting-sort ()
 
Like sorting in sqlite, there are ascending and descending orders, in which the ascending order is represented by 1, and the descending order is represented by-1. jingdong. find (). sort ({"time": 1 })
Index-ensureIndex ()

Indexes can greatly improve the query efficiency. If there is no index, MongoDB must scan each file in the set and select the records that meet the query conditions when reading data. The query efficiency of this full set of scans is very low, especially when processing a large amount of data, the query can take dozens of seconds or even a few minutes, which is undoubtedly very fatal to the performance of the website. An index is a special data structure. An index is stored in a dataset that is easy to traverse and read. An index is a structure that sorts the values of one or more documents in a database set.

db.COLLECTION_NAME.ensureIndex({KEY:1|-1})
> Db. shiyanlou. ensureIndex ({"name": 1}) #1 indicates Ascending Order-1 indicates descending order
 
 
> db.shiyanlou.ensureIndex({"user_id":1,"name":1},{background:1})
The following table lists the ensureIndex parameters:
Parameters Type Description
Background Boolean Do you want to block other database operations when creating an index? The default value is false.
Unique Boolean Indicates whether the created index is unique. The default value is false.
Name String Index name. If not specified, the system automatically generates
DropDups Boolean Whether to delete duplicate records when creating a unique index. The default value is flase.
Sparse Boolean No index is enabled for fields that do not exist in the document. The default value is false.
ExpireAfterSeconds Integer Sets the survival time of the Set, in seconds.
V Index version Index version
Weights Document Index weight, ranging from 1 to 99999
Default-language String English by default
Language_override String The default value is language.
Aggregation-aggregate ()
db.COLLECTION_NAME.aggregate({$match:{x:1},{limit:NUM},$group:{_id:$age}})
$ Match: query, the same as find; $ limit: limit the number of displayed results; $ skip: Ignore the number of results; $ sort: sort; $ group: combine results based on a given expression.
> db.jingdong.aggregate([{$group:{_id:"$name", user:{$sum:"$user_id"}}}])
Name Description
$ Sum Sum
$ Avg Calculate the average value
\ $ Min and $ max Calculate the minimum and maximum values
$ Push Insert values into an array in the result document
$ AddToSet Insert a value to an array in the result document, but do not create a copy.
$ First Obtain the first document data by sorting the resource documents
$ Last Obtain the data of the last document by sorting the resource documents.
The aggregation pipeline of the MPs queue MongoDB delivers the results to the next MPs queue after processing the MongoDB documents in the same MPs queue. Pipeline operations can be repeated. Expression: process and output the input document. Expressions are stateless and can only be used to calculate documents in the current aggregation pipeline. They cannot process other documents. Several common operations in aggregation frameworks:
$ Project: modify the structure of the input document. It can be used to rename, add, or delete domains, or create computing results and nested documents. $ Match: used to filter data. Only documents that meet the conditions are output. $ Match uses the MongoDB standard query operation. $ Limit: used to limit the number of documents returned by the MongoDB aggregation pipeline. $ Skip: Skips a specified number of documents in the aggregation pipeline and returns the remaining documents. $ Unwind: splits an array field in the document into multiple entries, each containing a value in the array. $ Group: Groups Documents in the set for statistical results. $ Sort: Sorts input documents and outputs them. $ GeoNear: outputs ordered documents close to a certain geographical location.
> db.shiyanlou.aggregate([{$match:{user_id:{$gt:0,$lte:2}}},{$group:{_id:"user",count:{$sum:1}}}]){"_id":"user","count":2}

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.