MongoDB Data Query | Mongodb

Source: Internet
Author: User
Tags findone

1. Basic query ① Method Find (): Query db. collection name. Find ({conditional document}) ② method FindOne (): Query, returns only the first DB. Collection name. FindOne ({conditional document}) ③ method Pretty () : Formats the result of the DB. Collection name. Find ({conditional document}). Pretty () 2. The comparison operator # equals, the default is equal to the judgment, no operator # is less than, $lt Less-than # is less than or equal to, $lte less-t Han,equal # greater Than, $GT Greater-than # Less than or equal to, $gte greater-than,equal # does not equal, $ne not equal db.collecti On2.find ({name: ' Guo Jing '}) db.collection2.find ({age:{$gte: 18}}) 3. Logical operator ① logic and # default is logical Relationship # Example: Query age is greater than or equal to 18        , and the gender is true of the student Db.collection2.find ({age:{$gte: +}, gender:true}) ② logic or # using $or, the value is an array, each element in the arrays is JSON # example: Query for students older than 18, or with a gender of false Db.collection2.find ({$or: [{age:{$gt: 18}},{gender:false}]}) Note: Find () >&gt ; or condition of {} >> $or [] >> >> {condition a},{condition B} >> {domain: {logical character judgment}}③ or, Shared # example: Query age greater than 18 or name is Guo Jing, and and sex for boys Db.collection2.find ({$or: [{age:{$gt:},{name}: ' Guo Jing '}],gender:true}) 4. Scope Operator # $in | $nin # Example: Query year DB.C of students aged to 18,28Ollection2.find ({age:{$in: [18, 28]}}) # Here to note that the maximum and minimum are required in the table contains these numbers 5. Support Regular Expressions # Use//or $regex write regular Expressions # example: Db.coll  Ection2.find ({name:/^ yellow/}) Db.collection2.find ({name:{$regex: ' ^ Yellow '}}) 6. Custom Query # Use $where to write a function that returns the data that satisfies the criteria # Example: query for students greater than 30 years old Db.collection2.find ({$where: function () {return this.age >}}) 7.L Imit and Skip① Method limit (): reads the specified number of document # DB. Collection name. Find (). Limit (number) Db.collection2.find (). Limit (2) # attached: The specified parameter displays all documents in the collection ② method Skip (): Used to skip the specified number of document # DB. Collection name. Find (). Skip (number) Db.stu.find (). Skip (2) # attached: parameter n Umber indicates the number of skipped records, with the default of 0③limit () with Skip () # In order of precedence, skipping the specified number of documents, and then reading the specified number of document # query data Db.collection1.find (). Limit (4). Skip (5) Db.collection1.find (). Skip (5). Limit (4) 8. Projection--Select field to display Data #①db. Collection name. Find ({},{field name: 1, ...} ) Db.collection2.find ({},{name:1, gender:1}) # ' 1 ': Indicates that the display field is not set to show that the #② is special: The _id column is displayed by default, # If it is not displayed Need to be explicitly set to 0 Db.collecTion2.find ({},{_id:0,name:1,gender:1}) 9. Sort--Sort the result set parameter 1 to arrange the parameters in ascending order-1 bits in descending order # DB. Collection name. Find (). Sort ({field: 1.    ..}) #--According to the sex descending, and then according to the Age ascending db.collection2.find (). Sort ({gender:-1,age:1}) 10. Statistics ① Method Count (): Used to count the number of document bars in the result set 1.db. Collection Name        . Find ({condition}). Count () Db.collection2.find ({gender:true}). Count () #--Count the number of boys 2.db. Collection name. Count ({condition}) Db.collection2.count ({age:{$gt: 20}, Gender:true}) #-The number of boys with a statistical age greater than 11. de-Duplication ① method Distinct (): deduplication of field data, extraction of--db.    The collection name. Distinct (' de-weight field ', {condition}) db.collection2.distinct (' hometown ', {age:{$gt: 18}}) # Query for students older than 18 years, from which provinces # 4. Aggregate query 1. Basic syntax --Syntax db. The collection name. Aggregate ({pipe: {expression}}) attached: 1. Pipelines: In Unix and Linux, the output of the current command is generally used as input to the next command 2. Expression: Handling into the document and output 2. Common Expressions $sum: computational Synthesis, $sum: 1 is counted as one count $avg: Average $min: Gets the minimum $max: Gets the maximum value $push: Inserts a value into the result document to the first document data $fi RST: Gets the first document data $last based on the sort of the resource document: Gets the last document data according to the sort of the resource document 3. Common pipeline ① $group--Groups The documents in the collection, which can be used for statistical results--_id to represent the basis for grouping, using a     field is formatted as ' $ Field '       # count the total number of boys and girls Db.stu.aggregate ({$group: {_id:            ' $gender ', counter:{$sum: 1}})--pivot data # Statistics student gender and student name Db.stu.aggregate ({$group: {_id: ' $ Gender ', name:{$push: ' $name '}})--use $ $ROOT to To add the contents of the document to the array in the result set Db.stu.aggregate ({$group: {_id: ' $ge NDEr ', name:{$push: ' $ $ROOT '}}}) ② $match- -Modify the structure of the input document, such as renaming, adding, deleting fields, creating calculation results-for filtering data, outputting only eligible documents-using MONGODB's standard query operation # Query for students older than 20 Db.stu.agg Regate ({$match: {age:{$gt: 20}}) # Query the number of boys and girls older than 20 db.stu.aggregate ({$match:        {age:{$gt: 20}}},    {$group: {_id: ' $gender ', counter:{$sum: 1}}) ③ $project-Modify the structure of the input document, such as rename, add, delete field, create calculation result # query student's name, age db.stu.aggregate ({$proj ECT:{_ID:0,NAME:1,AGE:1}) # Query the number of boys, girls, Output db.stu.aggregate ({$group: {_id: ' $gender ', Coun        ter:{$sum: 1}}, {$project: {_id:0,counter:1}}) ④ $sort--Sort input document after output # query student information by age ascending B.stu.aggregate ({$sort: {age:1}}) # Query the number of boys and girls, descending by the number of Db.stu.aggregate ({$group: {_id: ' $gender ', cou nter:{$sum: 1}}, {$sort: {counter:-1}}) ⑤ $limit and $skip--$limit # Limit the number of documents returned by the aggregation pipeline #            Query 2 Student Information db.stu.aggregate ({$limit: 2})--$skip # Skip the specified number of documents and return the remaining documents # query student information starting with 3rd Db.stu.aggregate ({$skip: 2}) # statistics male, female number, according to the number of ascending, take 2nd data db.stu.aggregate ({$group: {_id: ' $gender ', counter:{$sum: 1}} {$sort: {counter:1}} {$skip: 1}                {$limit: 1}) ⑥ $unwind Field Split query-syntax--an array field in a document contains multiple values--split multiple bars based on the value under the field--each containing a value--db the array. The collection name. Ggregate ({$unwind: ' $ field Name '}) # $unwind Aggregation method contains two properties: Path: ' $ field name ' Preservenullandemp tyarrays:< Boolean > # do not fill in properties, default = < Boolean > False # without tag attribute name--constructs data Db.t3.insert (            [{"_id": 1, "Item": "A", "Size": ["S", "M", "L"]}, {"_id": 2, "item": "B", "Size": []}, {"_id": 3, "item": "C", "Size": "M"}, {"_id": 4, "item": "D"}, {"_id": 5, "item ":" E "," size ": null}])--View the results of the query, display the document Db.t3.aggregate ({$unwind: {path: ' $s for an empty array, no fields, NULL)  Ize ', Preservenullandemptarrays:true}})--View query results, do not display empty array, no fields, NULL document Db.t3.aggregate ({$unwind: ' $size '}) Equivalent to: Db.t3.aggregate ({$unwind: {path: ' $size ', Preservenullandemptyarrays:false}})

  

MongoDB Data Query | Mongodb

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.