Skip to content

Instantly share code, notes, and snippets.

@Abhinay-g
Last active April 24, 2019 13:23
Show Gist options
  • Save Abhinay-g/72fa81e17a5e6f8eafe3bfd4d7b4a759 to your computer and use it in GitHub Desktop.
Save Abhinay-g/72fa81e17a5e6f8eafe3bfd4d7b4a759 to your computer and use it in GitHub Desktop.
MongoDB reading data
>Intorduction
This module will consist of following
1) methods, Filters and Operators for Reading Data
2) query selector
3) Projection operator
>Operators
All command include a db.collectionName.MethodName({-parameter-})
parameter can be key value pair or it could be a Range
db.collectionName.MethodName({key:{$operator:value}})
This operarator can be comparison operator / logical operator / element operator / evaluate operator
basically operator are of 5 type
1) Query and Projection Operators
2) update operators
3) Aggregation pipeline stages
4) Aggregation pipeline operator
5) Query modifiers [deprecated]
In Data Reading section we will EXPLORE query and projector operator for reading and formatting data respectivly.
> Query selector and Projection operator
{Query selector operator} >comparison, logical, element, evaluation, array,comment, geoSpatial (finding nearest location)
{Projection operator} > {$ , $elemMatch, $meta, $slice}
> Comparison operator
we pass a new key-value pair instead of a a value in conparison operator
example : db.Movies.find({runtime:{$lt:60}})
> Querying embeded fields
these can be a key of an embeded document or a key of an Array
example : db.Movies.find({"rating.average":{$gt:7}})
db.Movies.find({genre:"Drama"})
Note : genres is an Array Fields, above query will return element containing "Drama"
but if we write query like below we will get entry which contain only "Drama"
db.Movies.find({genre:["Drama"]})
Thumbrule : to access embeded fields use "parentKey.ChildKey" syntax
>Understanding in and nin
this is used to check if something in in some array AS here we have multiple value against one field
example : db.Movies.find(runtime:{$in:[30,60]})
> understnding or Nor
use MoviesDatabase
this is a logical operator where we will check multiple or condition
example : db.Movies.find({$or:[{runtime:{$lt:35}},{runtime:{$gt:60}}]})
> understanding And* operator
example : a) db.Movies.find({$and:[{runtime:{$gt:35}},{runtime:{$lt:60}}]})
b) db.Movies.find({runtime:{$gt:35,$lt:60}}).count()
c) db.Movies.find({runtime:{$gt:35},runtime:{$lt:60}}).count()
A and B will return same value but with C case we will recieve different output
as second runtime key-value will overlap with first key-value, so it will return value matching second pattern
Logical operator are done, now we will explore Element operator
> Element Operator
ther are tw otype of element operator
1 ) exixts : this is used to check if some field exists or not
example: db.Colelction.find(key:{exists:true}).pretty() >> this will return where key exixts
2 ) type : this is used to filter key based on some type
example: db.collections.find({key:{$type:"number"}}) >> this will only return value which are numbers
> Evaluation Operator
1) $regex
/--expression--/ is used to attach a regex into find()
db.Movies.find({summary:{$regex:/musical/}}).pretty()
**** Note : text index is efficient way to search value from text in mongoDB , this can be found in indexes module
2) $expr ** this replaced $where from previous version
use financialData
This is used to evaluate some kind of expression.
example we want sales records where volume > target: here we got two parameter where we need comparision
db.sales.find({$expr:{$gt:["$volume","$target"]}}).pretty()
This is the simplest example where two fields are related to find some output
now comes complex expression
db.sales.find(
{
$expr: {
$gt: [
{
$cond: {
$if: { $gte: ['$volume', 190] },
then: { $subtract: ['$volume', 30] },
else: '$volume'
}
},
'$target'
]
}
}
).pretty()
>Quering array
$size : this return the element with size specefied
Example : db.user.find({hobbies:{$size:3}}).pretty()
** $size is only available for equality operator we can not query something less then or greater than size
$all : this is used when we search soemthing within array
we can user traditional find({arrayname:["value1","value2"]}) , but this lookup preserves the oeder
ie it will only show ["value1","value2"] not ["value2","value1"]
to solve this we got $all
db.collection.find({arrayName:{$all:["value1","value2"]}}).pretty()
$elemMatch:
db.user.find({$and:[{"hobbies.title":"sports"},{"hobbies.frequency":3}]}).pretty()
above query will give wrong answer as $and operator with parentKey.Childkey will look for parameter matching within multiple odcuments
so it can check for title in one document and frequency in other document , to avoid this we have $elemMatch
db.user.find({hobbies:{$elemMatch:{title:"sports",frequency:{$gte:3}}}}).pretty()
> Understanding cursors
A pointer to the result set of a query, cursor is stored on server side . by default mongodb return data in batches, cursor is just a
way of accessing data from mongo server.
there are two methods can be applies to find() method
find().toArray(function(err,docs){}) this will force mongodb server to return entire result set in one shot.
find().forEach((docs,error)=>{}) This will iterate data over resultset, this is more effieient than toArray() because it takes advantage
of batch data.
> Applying Cursor
we can associate a variable on a cursor like below
const cursorData=db.Movies.find() /// this will assisgn a cursor to the resultset
now to iterate over result set use below code
cursorData.next() // this will return next document
To iterate over all data we do following thing
cursorData.forEach(data=> printjson(data)) // this will print all data one by one
remember if you execute .forEach after next() then forEach will get data from point where next() stoped
>sorting data
db.Movies.find().sort({"rating.average":1,runtime:-1}).pretty()
1 for accending , -1 for decending
>Skipping and limiting
skipiing and limiting combination can be used in pagination
when some body skip to next page skip kan be used , after skip we do not have control on next number of records
for that we have limit
example db.Movies.find().skip(100).limit(10) // this will skip first 100 records then return only next 10 records
by default limet is 20.
* Note here order of execution doesn't matter but we will learn about this in Aggregation framework
>Projection
Projection is a second parameter of find method
db.Movies.find({},{genres:1}) // this will return only genres, processing is done of server side
> Projection with arrays
Lets we are projecting array but you want to access perticular value out of array
Example: we lookk for genres array with "Drama" but we want to find out which "Drama" movies have "Horrror"
db.Movies.find({generes:"Drama"}, {genres:{$ememMatch:{$eq:"Horror"}}})
first we will have all the documetn with "Drama" as a part of geeneres array
then it will filter ir based of all the element of generes
>Slicing the output array
db.Movies.find({genres:"Drama"},{name:1,generes:{$slice:2}}).pretty()
this is used to limit number of element of an array
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment