Query documents
All operators
db.collection.find
- find returns cursor, findOne returns single document
Docs
Syntax
Equals
In
AND
- $and exists
OR
- (.) $nor also exists (inverse of OR)
- or = A || B || C
- nor = !(A || B || C) = !A && !B && !C
- (.) $not also exists (useful to inverse any query)
Like
- so use regex pattern for case-insensitive matches
- this may hit performance (when we search between..etc) instead use text indices
Object
Consider following
Array
Object Array
We can use same syntax like object for object array, but
Consider Example :
db.products.find({"gradesObjArr.mean": {$gt: 99}})issue with above syntax is, when we have multi condition then all wont apply on same array element.
db.products.find({ //test it"gradesObjArr.mean": {$gt: 50},"gradesObjArr.avg": {$gt: 100}})let doc = {name:'test',gradesObjArr:[{mean : 60, //> 50avg:60},{mean : 10,avg:110 //> 100 , so current document is selected}]}
Nested Object Array
Null + exists
type has number value, also name alias
- $exists + grades: null check
- $exists + grades -> $ne : null check
$expr
- docs
- useful to compare fields from the same document
- check $cond example in above docs link
- $expr with other operators
- To compare dates
Projection
Note: to give alias name (.)
elemMatch in projection
(don't use - prefer aggregation pipeline)
say in array, we want to project some matching 1st element
$elemMatch projection returns only the first matching element from the array.
consider
$slice in projection
controls the number of items of an array that a query returns
first five items in an array in the comments field
- the last five items in array
- will only return 10 items, after skipping the first 20 items of that array.
- returns 10 items as well, beginning with the item that is 20th from the last item of the array.
db.collection.sort
Docs
Syntax
Examples
Find one (Docs)
Aggregation pipeline, the map-reduce function, and single purpose aggregation methods
.find().count() method exists
Note : After find(), we do .toArray(), forEach() loop to execute cursor in application.
Better write queries in js files (formatted) & execute that file in shell