MongoDB (Advanced)

26
MongoDB (Advanced) By Amit Kumar

description

In this presentation, Amit explains querying with MongoDB in detail including Querying on Embedded Documents, Geospatial indexing and Querying etc.

Transcript of MongoDB (Advanced)

Page 1: MongoDB (Advanced)

MongoDB (Advanced)

By Amit Kumar

Page 2: MongoDB (Advanced)

Agenda

1. MongoDB beginner recap

2. What is db ??

3. Wrapped Queries

4. Query using Modifiers

5. Upsert (SaveOrUpdate Query)

6. Updating Multiple Documents

7. Specifying Which Keys to Return

8. AND/OR Queries

9. Querying on Embedded Documents

10. Cursors

11. Geospatial Indexing

Page 3: MongoDB (Advanced)

MongoDB beginner recap

1. A JSON object is called A Document. (Row in MySQL).

2. Group of documents are called Collection. (Table in MySQL).

3. To install MongoDB: sudo apt-get install mongodb;

4. To start MongoDB: mongo;

5. To show database names: show dbs;

6. To select Database: use dbName;

7. To get 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. To get matching up to 20 Documents:

db.collectionName.find();

Page 4: MongoDB (Advanced)

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. To remove All Documents from A Collection: db.collectionName.remove();

14. To update Document: db.collectionName.update(document1, document2);

// it takes (at least) two parameters: the first is the 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"}}

Page 5: MongoDB (Advanced)

What is db??

On startup, the shell connects to the test database on a MongoDB server and assigns this database connection

to the global variable db.

If we look at the db variable, we can see that it refers to the test database.

> db

test

Page 6: MongoDB (Advanced)

Store JavaScript1. 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.

Page 7: MongoDB (Advanced)

Wrapped Queries

1. Like Query:

db.Tag.find( {name:/^term/} );

2. Sort Query:

1 for ascending sort

-1 for descending sort

db.Tag.find().sort( {userName:-1, age:1} );

3. Limit Query:

db.Tag.find().limit(10);

Page 8: MongoDB (Advanced)

Wrapped Queries ...

4. Count Query:

db.Tag.find().count();

5. Skip Query:

db.Tag.find().skip(50);

NOTE: A good way of figuring out what a function is doing is to

type it without the parentheses. This will print the

JavaScript source code for the function.

Page 9: MongoDB (Advanced)

Query using Modifiers

1. Not Equal Modifier($ne):

db.Tag.find({firstProperty : {$ne : 3}});

2. Greater/Less than Modifier($gt, $lt, $gte, $lte):

db.Tag.find({firstProperty : {$gt : 2}});

db.Tag.find({firstProperty : {$lt : 2}});

db.Tag.find({firstProperty : {$gte : 2}});

db.Tag.find({firstProperty : {$lte : 2}});

Page 10: MongoDB (Advanced)

Query using Modifiers ...

3. Increment Modifier($inc):

db.Tag.update( {thirdProperty:"Hello19"},

{"$inc": {firstProperty:2}} )

4. Set Modifire($set):

db.Tag.update( {thirdProperty:"Hello19"},

{"$set": {fourthProperty: "newValue"} } )

NOTE: Key-value will be created if the key doesn't exists yet in the case of both $set and $inc. $inc works for

integers only. $set works for all. $inc Incrementing is

extremely fast, so any performance penalty is negligible.

Page 11: MongoDB (Advanced)

Query using Modifiers ...

5. Unset Modifier($unset):

db.Tag.update( {thirdProperty:"Hello19"},

{"$unset": {fourthProperty: "anything"} } )

6. Push Modifire($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 exists and creates a new array if it

does not.

Page 12: MongoDB (Advanced)

Query using Modifiers ...

7. AddToSet Modifier($addToSet):

db.Blog.update( {title:"1st Blog"}, { $addToSet:

{comment:"2nd Comment"} } );

8. Pop Modifier($pop):

comment = -1 remove an element from start.

comment = 1 remove an element from end

db.Blog.update( {title:"1st Blog"}, {$pop:{comment:-1} } );

Page 13: MongoDB (Advanced)

Query using Modifiers ...9. Pull Modifier($pull):

db.Blog.update({title:"1st Blog"}, {$pull:{comment:"2st Comment"}})

NOTE: Pulling removes all matching documents, not just a single

match.

10. Position Operator($): The positional operator updates only

the first match.

db.embededDocument.update({"comments.author" : "John"},

{"$inc" : {"comments.0.votes" : 1}})

db.embededDocument.update({"comments.votes" : 3},

{"$set" : {"comments.$.author" : "Amit Kumar"}})

Page 14: MongoDB (Advanced)

Upsert(SaveOrUpdate Query)

An upsert is a special type of update.

1. If no document is found that matches the update criteria, a new document will be created by combining the criteria and update documents.

2. If a matching document is found, 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 on Id only.

Page 15: MongoDB (Advanced)

Updating Multiple Documents

Updates, by default, update only the first document found that

matches the criteria. If there are more matching documents, they

will remain unchanged. To modify 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)

Page 16: MongoDB (Advanced)

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})

Page 17: MongoDB (Advanced)

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:["5th Comment", "1st Comment"]} } )

2. "$or" is more 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".

Page 18: MongoDB (Advanced)

AND Queries

There are two ways to do an AND query.

1. "$all" can be used to query for a variety of values for a single key.

db.Blog.find( {comment:{$all:["5th Comment", "1st Comment"]} } )

NOTE: Below will do exact match and order too matters, if order will change then it will not match.

db.Blog({"comment" : ["5th Comment", "comment1st Comment"]})

Page 19: MongoDB (Advanced)

AND Queries ...

2. Simple queries are and queries. It can 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"})

Page 20: MongoDB (Advanced)

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" } } )

This query 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"})

Page 21: MongoDB (Advanced)

Cursors

The database returns results from find using a cursor. If we do not store the results in 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. It waits until you actually start requesting results to 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});

Page 22: MongoDB (Advanced)

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". To create the index, use the ensureIndex method:

db.User.ensureIndex({"username" : 1})

Page 23: MongoDB (Advanced)

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 a current location.

1. MongoDB provides a special type of index for coordinate plane queries, called a geospatial index.

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"})

Page 24: MongoDB (Advanced)

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}}

Page 25: MongoDB (Advanced)

Geospatial Indexing ...

Geospatial queries can be performed in two ways:

1. As a normal query (using find): The find approach is similar to 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 query point.

db.runCommand({geoNear : "User", near : [40, -73], num : 10});

Page 26: MongoDB (Advanced)

Thank You