MongoDB query, index, and aggregation

Source: Internet
Author: User
Tags mongodb query sorts sqlite

Organize from

Https://www.shiyanlou.com/courses/running/77

Initializing the MongoDB database
>Use chenshiswitched to DB chenshi> db.createcollection ("Shiyanlou")#无参数 {"OK":1}> Show CollectionsshiyanlouSystem.indexes> userdoc1= ({"USER_ID":1,"Name":"Cloud","State":"Active","Actor":"User","E-mail":The test@qq. com ","Vm_num":2,"Time": [{"Date":"2014-08-12","Hour":"10:53 PM"}]}) > userdoc2= ({"USER_ID":2,"Name":"Testadmin","State":"Active","Actor":"Admin", "e-mail":  "Test @qq. com",  "Vm_num": 2, "time": [{ "Date":  "2014-08-11",  "hour": " name ": " Peter ",  "position":  "Teacher"}) > Db.shiyanlou.insert (USERDOC1) Writeresult ({ "ninserted": 1}) > Db.shiyanlou.insert ( USERDOC2) Writeresult ({ "ninserted": 1}) > Db.shiyanlou.insert (Doc1) writeresult ({ "ninserted": 1}) 

/span>
Query statements

Db. Collection_name.find (Parameter) Example:

> db.shiyanlou.find()

Document information, this directive is equivalent to the SELECT * FROM table_name in SQLite

Conditional operator 1

The conditional operators in MongoDB are:

    • (>) greater than-\ $GT #greate
    • (<) less than-\ $lt #low
    • (>=) greater than or equal to-\ $gte #equal
    • (<=) less than or equal to-\ $lte

Example:

db.shiyanlou.find({user_id:{$gt:1}})> db.shiyanlou.find({user_id:{$lte:2,$gt:1}})

Conditional operator 2

Grammar:

$type

The value of type:

    • Double Type-1
    • String-2
    • Objects-3
    • Array-4
    • Binary Data-5
    • Object ID-7
    • Boolean Type-8
    • Data-9
    • Null-10
    • Regular Expressions-11
    • JS Code-13
    • Symbol-14
    • Scoped JS Code-15
    • 32-bit integer number-16
    • Timestamp-17
    • 64-bit integer number-18
    • Min key-255
    • Max key-127

Example:

> db.shiyanlou.find({"name":{$type:2}})

Find name is a string of document records

Limit and Skip

Reads a specified number of data records-limit

Example:

> db.shiyanlou.find().limit(1)

Reads a record, the default is the first line is read

Skips a specified number of data records while reading-skip

Example:

> db.shiyanlou.find().limit(1).skip(1)

Of course, you can also add parameters for find criteria to find more accurate

 
MongoDB sort-sort ()

As with the sort in sqlite there are ascending and descending, where ascending is indicated by 1, and descending with-1 means syntax:

db.COLLECTION_NAME.find().sort({KEY:1|-1})

Example:

> db.shiyanlou.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.

Grammar:

db.COLLECTION_NAME.ensureIndex({KEY:1|-1})

The same 1 stands for ascending, 1 for descending

Example:

> db.shiyanlou.ensureIndex({"name":1})

Optional parameters for Ensureindex ():

if not specified
parameter type description
background Boolean Build index to not block other database operations, default to False
unique Boolean If the index is unique, the default is
name string index, and the system automatically generates
dropdups Boolean whether duplicate records are deleted when a unique index is established, default Flase
sparse Boolean does not enable indexing for field data that does not exist for a document, default false
expireafterseconds integer Set the lifetime of the collection in seconds
v Index version revision number
weights Document index weight value, ranging from 1 to 99999
default-language string default to English
language_override string default value is language

Example:

> db.shiyanlou.ensureIndex({"user_id":1,"name":1},{background:1})
Iv. polymerization-aggregate ()

Grammar:

db.COLLECTION_NAME.aggregate({$match:{x:1},{limit:NUM},$group:{_id:$age}})

These parameters are optional

    • $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.

Example:

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

$name means to get the value of name

Aggregation expressions
name Description
$sum Calculate sum
$avg Calculate average
\ $min and $max Calculate minimum and maximum values
$push Inserting values into an array in the resulting document
$addToSet Inserts a value into an array in the resulting document, but does not create a copy
$first Get the first document data based on the ordering of the resource documents
$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.

Example:

 > db.shiyanlou.aggregate ([{ $match: {User_id:{ $gt: 0, $lte: 2}}},{ $group: {_id: "user", Count : { $sum: 1}}]) { "_id":  "user",  "Count": 2}    
  &NBSP;             
  &NBSP;   

MongoDB query, index, and aggregation

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.