In this presentation, Amit explains querying with MongoDB in detail including Querying on Embedded Documents, Geospatial indexing and Querying etc.
The tutorial includes a recap of MongoDB, the wrapped queries, queries which are using modifiers, Upsert (saving/ updating queries), updating multiple documents at once, etc. Moreover, it gives a brief explanation about specifying which keys to return, the AND/OR queries, querying on embedded documents, cursors and Geospatial indexing. The tutorial begins with a section about MongoDB which includes steps to install and start MongoDB, to show and select Database, to drop collection and database, steps to insert a document and get up to 20 matching documents. Furthermore, it also includes steps to store and use Javascript functions on the server side.
The next section after the MongoDB section is about wrapped queries and queries using modifiers which includes the types of wrapped queries which are used like LikeQuery, SortQuery, LimitQuery, SkipQuery. It also includes the types of queries using modifiers like NotEqualModifier, Greater/Lesser modifier, Increment Modifier, Set Modifier, Unset Modifier, Push Modifier etc. Then comes the section about Upsert (Save or update). There are steps mentioned for saving or updating queries in this section.
At the same time, there are steps to update multiple documents altogether. The next section which is called “specifying which keys to return” talks about ways to specify the keys the user wants. After this section comes OR/AND query. It informs us about the general steps to do an OR query. Also, it includes the general steps to do an AND query. After this section comes another section called “querying on embedded document” which tells the user about ways of querying for an embedded document.
One of the important sections of this tutorial is about cursors, uses of a cursor and also methods to chain additional options onto a query before it is performed. Following is a section about indexing which talks about indexing as a term and how indexing helps in improving the query’s speed. At the end is a section which gives a brief explanation on geospatial indexing which is another type of query that became common with the emergence of mobile devices. Also, it includes the ways geospatial queries can be performed.
4. MongoDB beginner recap
1. A JSON object iscalled A Document. (Row in MySQL)
2. Group of documents are called Collection. (Table in MySQL)
3. To install MongoDB: sudo apt-get installmongodb;
4. Tostart MongoDB: mongo;
5. To show database names:showdbs;
6. To select Database: usedbName;
7. Toget All Collections: show collections; OR show tables;
//Every document stored in MongoDB must have an "_id"key
8. To insert A Document: db.collectionName.insert(document);
9. Toget matching up to 20 Documents:
db.collectionName.find();
5. MongoDB beginner recap ...
10.To get first document:db.collectionName.findOne();
11. To drop Collection:db.collectionName.drop();
12. To drop Database:db.dropDatabase();
13.Toremove All Documents from A Collection:
db.collectionName.remove();
14. To update Document: db.collectionName.update(document1,
document2);
// it takes (at least) two parameters: the firstisthe criteria to
find which document to update. And second is the new
document.
15.Documents can contain entire documents, embedded as
values in a parent document, eg.
{"x": {"foo":"bar"}}
6. What is db??
On startup, the shell connects to the test database on a
MongoDB server and assigns thisdatabase connection
to the global variable db.
Ifwe look at the db variable, we can see that it refers to the
testdatabase.
>db
test
7. Store JavaScript
1. MongoDB comes with a JavaScript shell that allows interaction with a
MongoDB instance from the command line
2.We can store and use JavaScript functions and values on the server side
9. Wrapped Queries ...
4. CountQuery
db.Tag.find().count();
5. SkipQuery
db.Tag.find().skip(50);
NOTE:A good way of figuring out what a function isdoing isto
type it without the parentheses. This will print the
JavaScript source code for the function.
11. Query using Modifiers ...
3. IncrementModifier($inc)
db.Tag.update( {thirdProperty:"Helo19"},
{"$inc": {firstProperty:2}})
4. SetModifire($set)
db.Tag.update( {thirdProperty:"Helo19"},
{"$set":{fourthProperty: "newValue"}})
NOTE:Key-value will be created if the key doesn't existsyet in the case of both
$set and $inc. $inc works for integers only. $set works for all. $inc Incrementing
isextremely fast, so any performance penaltyisnegligible.
12. Query using Modifiers ...
5. UnsetModifier($unset)
db.Tag.update( {thirdProperty:"Helo19"},
{"$unset": {fourthProperty: "anything"}})
6. PushModifire($push)
db.Blog.update( {title:"1st Blog"},{$push:
{comment:"1st Comment"}});
NOTE:"$push" adds an element to the end of an array if the
specified key already existsand creates a new array if it
does not.
13. Query using Modifiers ...
7. AddToSetModifier($addToSet)
db.Blog.update( {title:"1st Blog"},{$addToSet:
{comment:"2nd Comment"} });
8.PopModifier($pop)
comment =-1remove an element from start.
comment =1 remove an element fromend
db.Blog.update( {title:"1stBlog"},{$pop:{comment:-1} });
14. Query using Modifiers ...
9. Pul Modifier($pull)
db.Blog.update({title:"1st Blog"},{$pul:{comment:"2st Comment"}})
NOTE:Pulling removes all matching documents, not justa single
match.
10.PositionOperator($)The positional operator updates only
the firstmatch.
db.embededDocument.update({"comments.author" :"John"},
{"$inc" :{"comments.0.votes":1}})
db.embededDocument.update({"comments.votes" :3},
{"$set": {"comments.$.author" : "AmitKumar"}})
15. Upsert(SaveOrUpdate Query)
An upsert isa special type of update.
1. Ifno document isfound that matches the update criteria, a new document
will be created by combining the criteria and update documents.
2. Ifa matching document isfound, it will be updated normally.
db.Tag.update(document1, document2, true);
db.Tag.update({secondProperty:”Jav”}, {"$inc":{"firstProperty":100}},true)
db.Tag.save(document)
Note: save works onId only.
16. Updating Multiple Documents
Updates, by default, update only the first document found that
matches the criteria. Ifthere are more matching documents, they
will remain unchanged. Tomodify all of the documents matching
the criteria, you can pass true as the fourth parameter to update.
db.Tag.update(document1, document2, false, true);
db.Tag.update({secondProperty:/J/}, {"$inc":{"firstProperty":100}},false, true)
17. Specifying Which Keys to Return
Sometimes, you do not need all of the key/value pairs in a
document returned. If this is the case, you can pass a second
argument to find (or findOne) specifying the keys you want. This
reduces both the amount of data sent over the wire and the time
and memory used to decode documents on the client side.
db.Tag.find({}, {_id:0,firstProperty:1})
18. OR Queries
There are two ways to do an OR query.
1."$in"can be used to query for a variety of values for a single key.
db.Blog.find( {comment: {$in:["5thComment", "1stComment"]} })
2."$or"ismore general; it can be used to query for any
of the given values across multiple keys.
db.Tag.find( {$or:[{firstProperty:0},{secondProperty:/J/} ]})
NOTE:The opposite of "$in"is"$nin".
19. AND Queries
There are two ways to do an AND query.
1."$al" can be used to query for a variety of values for a single key.
db.Blog.find( {comment:{$al:["5th Comment", "1stComment"]} })
NOTE: Below will do exact match and order too matters, if order will change
then it will notmatch.
db.Blog({"comment" : ["5thComment", "comment1stComment"]})
20. AND Queries ...
2.Simple queries are and queries. Itcan be used to query for any
of the given values across single/multiple keys.
db.Tag.find( {firstProperty:0, secondProperty:/J/} )
db.Blog.find({comment:"5th Comment",comment:"1st Comment"})
21. Querying on Embedded Document
There are two ways of querying for an embedded document.
1.Querying for an entire embedded document works identically to a normal
query.
db.User.find( {name: {first:"Amit",last:"Kumar"}})
Thisquery will do exact match and order too matters, if order will change then
it will not find.
2.Querying for its individual key/value pairs.
db.User.find({"name.first" : "Amit","name.last" :"Kumar"})
22. Cursors
The database returns results from find using a cursor. If we do not store the
resultsin a variable, the MongoDB shell will automatically iterate through
and display the first couple of documents. When you call find, the shell
does not query the database immediately. Itwaits until you actually start
requesting resultsto send the query, which allows you to chain additional
options onto a query before it is performed. Almost every method on a
cursor object returns the cursor itself so that you can chain them in any
order. For instance, all of the following are equivalent
>var cursor =db.Tag.find().sort({"x":1}).limit(1).skip(10);
>var cursor =db.Tag.find().limit(1).sort({"x":1}).skip(10);
>var cursor =db.Tag.find().skip(10).limit(1).sort({"x":1});
23. Indexing
Indexes are the way to make queries go vroom. Suppose that you are
querying for a single key, such as the following:
db.User.find({"username":"mark"})
When only a single key is used in the query, that key can be indexed to
improve the query’s speed. In this case, you would create an index on
"username". Tocreate the index, use the ensureIndex method:
db.User.ensureIndex({"username":1})
24. Geospatial Indexing
There is another type of query that is becoming increasingly common
(especially with the emergence of mobile devices): finding the nearest N
things to acurrent location.
1. MongoDB provides a special type of index for coordinate plane queries,
called a geospatialindex.
2. A geospatial index can be created using the ensureIndex function, but by
passing "2d" as a value instead of 1 or -1:
db.User.ensureIndex({"location" :"2d"})
25. Geospatial Indexing ...
The "location" key must be some type of pair value, that is, a two-element
array or embedded document with two keys.The keys can be anything:
{"location" : [0,100]}
{"location" : {"x":-30,"y": 30 }}
{"location" :{"latitude" : -180,"longitude" :180 } }
{"location" : {"foo": 0,"bar" :1}}
26. Geospatial Indexing ...
Geospatial queries can be performed in two ways:
1. As a normal query (using find): The find approach issimilarto performing a
nongeospatial query, except the conditional "$near" is used. It takes an
array of the two target values:
db.User.find({"location" : {"$near": [40,-73]}})
2. GeoNear command: ”geoNear” also returns the distance of each result
document from the querypoint.
db.runCommand({geoNear : "User",near : [40,-73],num :10});
27. Contact us
Here’s how TOTHENEW
uses MongoDB to create a
rich experience for your
customers!
Click Here To Know More!
Have more queries
related to MongoDB?
Talk To Our Experts!
Our Office
Client
Location