Find Method
DB. collection_name.find ();
Query all results:
Select * from users;
DB. Users. Find ();
Specify the columns (KEYS) returned ):
Select name, skills from users;
DB. Users. Find ({},{ 'name': 1, 'skills': 1 });
Note: The first {} puts the where condition and the second {} specifies the columns to display and not to display (0 indicates not to display 1 indicates to display)
Where condition:
1. Simple equals:
Select name, age, skills from users where name = 'hurry ';
DB. Users. Find ({'name': 'hurry'}, {'name': 1, 'age': 1, 'skills': 1 });
2. Use and
Select name, age, skills from users where name = 'hurry' and age = 18;
DB. users. find ({'name': 'hurry', 'age': 18}, {'name': 1, 'age': 1, 'skills': 1 });
3. Use or
Select name, age, skills from users where name = 'hurry' or age = 18;
DB. users. find ({'$ or': [{'name': 'hurry'}, {'age': 18}]}, {'name': 1, 'age ': 1, 'skills': 1 });
4. <, <=,>,> =($ Lt, $ LTE, $ GT, $ GTE)
Select * from users where age> = 20 and age <= 30;
DB. Users. Find ({'age': {'$ gte': 20,' $ LTE ': 30 }});
5. Use in, not in ($ in, $ Nin)
Select * from users where age in (10, 22, 26 );
DB. Users. Find ({'age': {'$ in': [10, 22, 26]});
6. Match null
Select * from users where age is null;
DB. Users. Find ({'age': NULL );
7. Like (MongoDB supports regular expressions)
Select * from users where name like "% HURRY % ";
DB. Users. Find ({Name:/Hurry /});
Select * from users where name like "Hurry % ";
DB. Users. Find ({Name:/^ hurry /});
8. Use distinct
Select distinct (name) from users;
DB. Users. Distinct ('name ');
9. Use count
Select count (*) from users;
DB. Users. Count ();
10. array query (MongoDB exclusive)
If skills is ['java', 'python']
DB. Users. Find ({'skills': 'java'}); this statement can be matched successfully.
$ All
DB. Users. Find ({'skills': {'$ all': ['java', 'python']}) skills must contain both Java and Python
$ Size
DB. Users. Find ({'skills': {'$ size': 2}) Unfortunately, $ size cannot be combined with $ lt.
$ Slice
DB. Users. Find ({'skills': {'$ slice: [1, 1]})
The two parameters are offset and return quantity respectively.
11. query embedded documents
12. Powerful $ where Query
DB. Foo. Find ();
{"_ Id": objectid ("4e17ce0ac39f1afe0ba78ce4"), "A": 1, "B": 3, "C": 10}
{"_ Id": objectid ("4e17ce13c39f1afe0ba78ce5"), "A": 1, "B": 6, "C": 6}
What if I want to query the document B = C?
> DB. Foo. Find ({"$ where": function (){
For (VAR current in this ){
For (VAR other in this ){
If (current! = Other & this [current] = This [other]) {
Return true;
}
}
}
Return false;
}});
{"_ Id": objectid ("4e17ce13c39f1afe0ba78ce5"), "A": 1, "B": 6, "C": 6}