1. Search by Condition:
Db.users.find ({"Name": "MM1"})
The second parameter of 2.find can specify the field to return: Here 1 indicates the field to be displayed, and 0 indicates the field to be rejected
Db.users.find ({"Name": "MM1"},{"name": 1, "Age": 1})
Db.users.find ({"Name": "MM1"},{"name": 0})
3. Query conditions: "$lt", "$lte", "$gt", "$gte": <,<=,>,>=
Db.users.find ({"Age": {"$lte": +, "$gte": 30}})
4. $in: Matches multiple values of the specified key; $nin and $in opposite $or match the values of multiple keys; $mod modulo, dividing the given value by the first number, and returning the data if the remainder equals the second number
Db.users.find ({"Age": {"$in": [20,25,30]}}) Db.users.find ({"age": {"$nin": [20,25,30]}}) Db.users.find ( {"$or": [{"Age": 20},{"Winner": "True"}]}) db.users.find ({"age": {"$mod": [20,5]}}) Db.users.find ({ "Age": {"$not": {"$mod": [20,5]}})
5. Query NULL:
Db.users.find ({"name":null// So the query will also match the document Db.users.fin ({"name": {"$in" ) that does not contain the key (name) : [ Null], "$exists":true// using $exists, you can accurately detect
6. Array query:
// query contains an array of apple and banana arrays Db.users.find ({"Fruit.1": "Banana"})// query array with a second value of banana, array starting from 0
7. Search by array Length:
Db.users.find ({"Fruit": {"$size": 3}})//$size cannot be used in combination with $gte, $lte, etc., by inserting a size field when updating data to resolve
8. $slice limit the number of documents returned
9. Try not to use $where: (1) The query speed is slow-and each document is converted from Bson to a JS object and then run through the $where expression; (2) cannot use index;
Ten. Limit,skip,sort
Db.users.find (). Limit (ten). Sort ({"name":1})
Avoid skipping over a large number of results using skip. Otherwise the speed will be very slow, the reason is: first to find these data, and then discard the data; Skip paging method is not used:
// (1) Get the first page of Var page1=db.users.find (). Sort ({"Date"-1}). Limit (+)//(2) Use the last date as the query condition to get the next page var lastest=nullWhlie (page1.hasnext)) { Lastest= Page1.next (); } var page2=db.users.find ({"date": {"$GT": Lastest.date}}). sort ({"Date": -1}). Limit (20)
11. Get Random Documents: Insert a random field when you save the data, and search for the document based on the generated random number
// Insert Data db.users.insert ({"Name": "One", "Age": $, "random": Math.random ()}) Db.users.insert ({"name": " One "," Age ": $," random ": Math.random ()}) Db.users.insert ({" name ":" One "," Age ":" Random ":math.random () }) Db.users.insert ({"name": "One", "Age": $, "random": Math.random ()}) Db.users.insert ({"name": "11", " Age ": $," random ": Math.random ()})// query random document var random=math.random ();d B.users.find ({ "random": {"$gt": Random})//If empty, you can change to $lt