Search This Blog

Sunday 27 April 2014

Quiz on MongoDB - Part-02

## Implementation Using JAVA DRIVER
 ======================================
@NOTE: new BasicDBObject() is same as '{}' in mongo shell...given you have a hands-on exp of querrying over mongo-shell ,Keeping this in mind will help a lot while writing Code for JAVA DRIVER to query mongoDB.

 #  Java Driver: Representing Documents
How would you create a document using the Java driver with this JSON structure:
{
   "_id" : "user1",
   "interests" : [ "basketball", "drumming"]
}

new HashMap().put("_id", "user1").put(Arrays.asList("basketball", "drumming"));
new BasicDBObject("_id", "user1").append("interests", "basketball", "drumming");
new DBObject("_id", "user1").append("interests", Arrays.asList("basketball", "drumming"));
new BasicDBObject("_id", "user1").append("interests", Arrays.asList("basketball", "drumming"));          [# CORRECT #]
 ------------------------------------------------------------------------------------------------------------
# Java Driver: Insert
Do you expect the second insert below to succeed?

        MongoClient client = new MongoClient();
        DB db = client.getDB("school");
        DBCollection people = db.getCollection("people");
        DBObject doc = new BasicDBObject("name", "Andrew Erlichson")
                .append("company", "10gen");
        try {
            people.insert(doc);      // first insert
            doc.removeField("_id");  // remove the "_id" field
            people.insert(doc);      // second insert
        } catch (Exception e) {
            e.printStackTrace();
        }

No, because the _id will be a duplicate in the collection
 No, because the removeField call will remove the entire document
 Yes, because the removeField call will remove the _id key added by the driver in the first insert                        [# CORRECT #]
 Yes, because the driver always adds a unique _id field on insert.
 ------------------------------------------------------------------------------------------------------------
#  Java Driver: find, findOne, count   : 'collection.find(), collection.findOne() , collection.count()'

 In the following code snippet:
        MongoClient client = new MongoClient();
        DB db = client.getDB("school");
        DBCollection people = db.getCollection("people");
        DBObject doc;
        xxxx
        System.out.println(doc);
Please enter the simplest one line of Java code that would be needed in place of xxxx to make it print one document from the people collection.
> doc = people.findOne(); [# ANSWER #]
------------------------------------------------------------------------------------------------------------
# Java Driver: Query Criteria
Given a collection of documents with two fields -- type and score -- what is the correct line of code to find all documents where type is "quiz" and score is greater than 20 and less than 90. Select all that apply.
scores.find(new BasicDBObject("score", new BasicDBObject("$gt", 20).append("$lt", 90));
scores.find(new BasicDBObject("type", "quiz").append("score", new BasicDBObject("$gt", 20).append("$lt", 90))) [# CORRECT #] 
scores.find(new BasicDBObject("type", "quiz").append("$gt", new BasicDBObject("score", 20)).append("$lt", new BasicDBObject("score", 90))) scores.find(QueryBuilder.start("type").is("quiz").and("score").greaterThan(20).lessThan(90).get()) [# CORRECT #]
------------------------------------------------------------------------------------------------------------

#  Java Driver: field Selection 
------------------------------------------------------------------------------------------------------------
# Java Driver: Dot Notation
In the following code snippet, what do you think will happen if there exists in the collection a document that matches the query but does not have a key called "media.url"?

DBObject findOneUrlByMediaType(DBCollection videos, String mediaType) {
    DBObject query = new BasicDBObject("media.type", mediaType);
    DBObject projection = new BasicDBObject("media.url", true);
       return videos.findOne(query, projection);
}

It will throw an exception
It will return an empty document
 It will return a document containing a single field containing the document's _id   [# CORRECT #]
 There is not enough information to know
------------------------------------------------------------------------------------------------------------
#  Java Driver: Sort, Skip and Limit
Supposed you had the following documents in a collection named things.
{ "_id" : 0, "value" : 10 }
{ "_id" : 1, "value" : 5 }
{ "_id" : 2, "value" : 7 }
{ "_id" : 3, "value" : 20 }

If you performed the following query in the Java driver:
collection.find().sort(new BasicDBObject("value", -1)).skip(2).limit(1);
which document would be returned?
The document with _id=0
The document with _id=1
 The document with _id=2
 The document with _id=3
-----------------------------------------------------------------------------------------------------------
#  Java Driver: Update and Remove
In the following code fragment, what is the Java expression in place of xxxx that will set the field "examiner" to the value "Jones" for the document with _id of 1. Please use the $set operator.

        # update using $set
        scores.update(new BasicDBObject("_id", 1), xxxx);

new BasicDBObject("$set",new BasicDBObject("examiner","Jones"))

-----------------------------------------------------------------------------------------------------------
# Java Driver -- findAndModify();

------------------------------------------------------------------------------------------------------------


## MongoDB Schema Design
=======================

What's the single most important factor in designing your application schema within MongoDB?
Making the design extensible.
 Making it easy to read by a human.
Matching the data access patterns of your application. [# CORRECT #]
 Keeping the data in third normal form.

 ----------------------------------------------------------------------------------------------------------
 Living Without Transactions
Which of the following operations operate atomically within a single document? Check all that apply.
Update [# CORRECT #]
findAndModify [# CORRECT #]
$addToSet(within an update)            [# CORRECT #]
$push within an update         [# CORRECT #]
------------------------------------------------------------------------------------------------------------
# One to One Relations
What's a good reason you might want to keep two documents that are related to each other one-to-one in separate collections? Check all that apply.
Because you want to allow atomic update of both documents at once.
 To reduce the working set size of your application. [# CORRECT #]
 To enforce foreign key constraints
 Because the combined size of the documents would be larger than 16MB [# CORRECT #]

 #  One to Many Relations
When is it recommended to represent a one to many relationship in multiple collections?
Always
Whenever the many is large
Whenever the many is actually few Never

------------------------------------------------------------------------------------------------------------
# Trees
Given the following typical document for a e-commerce category hierarchy collection called categories
{
  _id: 34,
  name : "Snorkeling",
  parent_id: 12,
  ancestors: [12, 35, 90]
}
Which query will find all descendants of the snorkeling category?
db.categories.find({ancestors:{'$in':[12,35,90]}})
db.categories.find({parent_id: 34})
 db.categories.find({_id:{'$in':[12,35,90]}})
 db.categories.find({ancestors:34}) [# CORRECT #]
-----------------------------------------------------------------------------------------------------------
#  Handling Blobs
Which of the following statements are true about GridFS?
GridFS stores large blobs in a single collection by breaking up the file into multiple pieces.
Each gridFS document is given a unique filename.
GridFS stores large blobs in two collections, one for metadata and one for the blob chunks.                            [# CORRECT #]
GridFS compresses your file on disk.

Wednesday 23 April 2014

Using DynamicQuery on multiples Entities in Liferay

Here's an example where i have used Dynamic Query to query two different Entities in Liferay .

Entity1 = ResourceBookingMapping
Entity1 = PromotionalItemsBooking
Also, see carefully the applicantsCriterion where lies the core-logic ..

Refer the complete code-extract below :
------------------------------------------------------------------------------------------------------------------------------------
List<ResourceBookingMapping> resourceBookingList = new ArrayList<ResourceBookingMapping>();
Criterion combineCriterion = null;
DynamicQuery query = DynamicQueryFactoryUtil.forClass(ResourceBookingMapping.class);
DynamicQuery applicantQuery = DynamicQueryFactoryUtil.forClass(PromotionalItemsBooking.class)
.setProjection(ProjectionFactoryUtil.property("referenceNo"))
.add(RestrictionsFactoryUtil.eq("userId", applicantId));
Criterion dateRangeCriterion = RestrictionsFactoryUtil.between("createDate",
                                                                                                new java.sql.Timestamp( date1.getTime()), 
                                                                                               new java.sql.Timestamp(date2.getTime()));
Criterion itemsCriterion = RestrictionsFactoryUtil.eq("itemId",itemId);
Criterion applicantsCriterion = PropertyFactoryUtil.forName("referenceNo").in(applicantQuery);
Criterion itemsUnionApplicantCriterion = RestrictionsFactoryUtil.and(itemsCriterion ,                                                                                                                                                                                                 applicantsCriterion);
if(applicantId>0 && itemId>0){
System.out.println(" Criterion -PromotionalItemsBooking :: itemId>0 && applicantId>0 ");
combineCriterion = RestrictionsFactoryUtil.and(dateRangeCriterion, itemsUnionApplicantCriterion);
}else if(applicantId>0){
System.out.println(" Criterion -PromotionalItemsBooking :: applicantId>0 ");
combineCriterion = RestrictionsFactoryUtil.and(applicantsCriterion, dateRangeCriterion);
query.add(combineCriterion);
}else if(itemId>0){
System.out.println(" Criterion -PromotionalItemsBooking :: itemId>0 ");
combineCriterion = RestrictionsFactoryUtil.and(itemsCriterion, dateRangeCriterion);
query.add(combineCriterion);
}else{
System.out.println(" Criterion -PromotionalItemsBooking :: only Date-Range Applicable ");
query.add(dateRangeCriterion);
}
resourceBookingList = ResourceBookingMappingLocalServiceUtil.dynamicQuery(query);
------------------------------------------------------------------------------------------------------------------------------------

Monday 14 April 2014

Quiz on MongoDB

[  $ ,^,$lt ,$gt,$lte,$gte, $or,$and,$regex ,$in ,$all, .DOT Notation]
cursor operators : .sort({name:-1}), .limit() ,  .skip()
.update() : [ $set , $inc]
----------------------------------------------------------------------------------------------------------
#Using $or
How would you find all documents in the scores collection where the score is less than 50 or greater than 90?
db.scores.find({$or:[{score:{$lt:50}},{score:{$gt:90}}]});
----------------------------------------------------------------------------------------------------------
What will the following query do?
db.scores.find( { score : { $gt : 50 }, score : { $lt : 60 } } );
Find all documents with score between 50 and 60
Find all documents with score greater than 50
Find all documents with score less than 60        [# CORRECT #]
None of the above
[## Q/A -REASON: being a JS Obj the first list of score will be replaced by the second @JS Promt...thus in order to achieve certain effect ,we could use $AND or $gt & $lt within the same inner query ,etc]
--------------------------------------------------------------------------------------------------------
#Querrying inside Array
Which of the following documents would be returned by this query?
db.products.find( { tags : "shiny" } );

{ _id : 42 , name : "Whizzy Wiz-o-matic", tags : [ "awesome", "shiny" , "green" ] } [# CORRECT #]
 { _id : 704 , name : "Fooey Foo-o-tron", tags : [ "blue", "mediocre" ] }
 { _id : 1040 , name : "Snappy Snap-o-lux", tags : "shiny" } [# CORRECT #]
 { _id : 12345 , name : "Quuxinator", tags : [ ] }
 ---------------------------------------------------------------------------------------------------------
 #Using $in & $all
 Which of the following documents matches this query?

db.users.find( { friends : { $all : [ "Joe" , "Bob" ] }, favorites : { $in : [ "running" , "pickles" ] } } )

{ name : "William" , friends : [ "Bob" , "Fred" ] , favorites : [ "hamburgers", "running" ] }
{ name : "Stephen" , friends : [ "Joe" , "Pete" ] , favorites : [ "pickles", "swimming" ] }
 { name : "Cliff" , friends : [ "Pete" , "Joe" , "Tom" , "Bob" ] , favorites : [ "pickles", "cycling" ] }[# CORRECT #]
 { name : "Harry" , friends : [ "Joe" , "Bob" ] , favorites : [ "hot dogs", "swimming" ] }
 -----------------------------------------------------------------------------------------------------------
#Querries with Dot[.] Notation
 Suppose a simple e-commerce product catalog called catalog with documents that look like this:

{ product : "Super Duper-o-phonic",
  price : 100000000000,
  reviews : [ { user : "fred", comment : "Great!" , rating : 5 },
              { user : "tom" , comment : "I agree with Fred, somewhat!" , rating : 4 } ],
  ... }
Write a query that finds all products that cost more than 10,000 and that have a rating of 5 or better..

 db.catalog.find({price:{$gt:10000},"reviews.rating":{$gte:5}}) [# ANSWER #]
 --------------------------------------------------------------------------------------------------------
 #Querying,Cursors
 Recall the documents in the scores collection:
{
"_id" : ObjectId("50844162cb4cf4564b4694f8"),
"student" : 0,
"type" : "exam",
"score" : 75
}
Write a query that retrieves exam -type documents, sorted by score in descending order, skipping the first 50 and showing only the next 20.

 db.scores.find({type:"exam"}).sort({score:-1}).skip(50).limit(20) [# ANSWER #]
 --------------------------------------------------------------------------------------------------------
 #Counting Results
 How would you count the documents in the scores collection where the type was "essay" and the score was greater than 90?
 db.scores.count({type:"essay",score:{$gt:90}})
  ----------------------------------------------------------------------------------
 #Updating wholesale Document
 Let's say you had a collection with the following document in it:
{ "_id" : "Texas", "population" : 2500000, "land_locked" : 1 }
and you issued the query:
db.foo.update({_id:"Texas"},{population:30000000})

{ "_id" : "Texas", "population" : 2500000, "land_locked" : 1 } 
{ "_id" : "Texas", "population" : 3000000, "land_locked" : 1 }
 { "_id" : "Texas", "population" : 30000000 } [# CORRECT #]
 { "_id" : ObjectId("507b7c601eb13126c9e3dcca"), "population" : 2500000 }  
  ----------------------------------------------------------------------------------
 .update() --$set
 For the users collection, the documents are of the form
{
"_id" : "myrnarackham",
"phone" : "301-512-7434",
"country" : "US"
}

Please set myrnarackham's country code to "RU" but leave the rest of the document (and the rest of the collection) unchanged. 
 > db.users.update({"_id" : "myrnarackham"},{$set:{"country":"RU"}}) [# ANSWER #]
   ----------------------------------------------------------------------------------
.update() --$unset
 Write an update query that will remove the "interests" field in the following document in the users collection.

    "_id" : "jimmy" , 
    "favorite_color" : "blue" , 
    "interests" : [ "debating" , "politics" ] 
}
 > db.users.update({"_id":"jimmy"},{$unset:{"interests":1}}) [# ANSWER #]
Further u can use the .find() mthd to verify the same 
> db.users.find({"_id" : "jimmy"})
{ "_id" : "jimmy", "favorite_color" : "blue" }
   ----------------------------------------------------------------------------------
 .update() -- USING $push, $pop, $pull, $pushAll ,$pullAll ,$addToSet
  db.array.update({"id:0"},{$push:{"a":55}})  [# INCORRECT #]
  db.array.update({"id":0},{$push:{a:55}})  [# CORRECT #]
-----------------------------------
 Suppose you have the following document in your friends collection:
{ _id : "Mike", interests : [ "chess", "botany" ] }

What will the result of the following updates be?
db.friends.update( { _id : "Mike" }, { $push : { interests : "skydiving" } } );
db.friends.update( { _id : "Mike" }, { $pop : { interests : -1 } } );
db.friends.update( { _id : "Mike" }, { $addToSet : { interests : "skydiving" } } );
db.friends.update( { _id : "Mike" }, { $pushAll: { interests : [ "skydiving" , "skiing" ] } } );

A> { _id : "Mike", interests : ["botany","skydiving","skydiving","skiing" ] } [# ANSWER #]
   ----------------------------------------------------------------------------------
#  .update() :-- Upserts {upsert:true}
upsert = update(if record foound) else insert the same [thts wht i make out of this.. ;-) ]
After performing the following update on an empty collection
db.foo.update({username:'bar'}, {'$set':{'interests':['cat', 'dog']}}, {upsert: true} );

What could be the state of the collection.
{ "_id" : ObjectId("507b78232e8dfde94c149949"), "interests" : [ "cat", "dog" ]}
 {"interests" : [ "cat", "dog" ], "username" : "bar" } 
 {} 
 { "_id" : ObjectId("507b78232e8dfde94c149949"), "interests" : [ "cat", "dog" ], "username" : "bar" } [# CORRECT #]
   ----------------------------------------------------------------------------------
 Multi-update  db.collection_name.update({},{$set:{}}{multi:true})
 Recall the schema of the scores collection:

{
"_id" : ObjectId("50844162cb4cf4564b4694f8"),
"student" : 0,
"type" : "exam",
"score" : 75
}
Give every document with a score less than 70 an extra 20 points.
> db.scores.update({score:{$lt:70}},{$inc:{score:20}},{multi:true}) [# ANSWER #]
   ----------------------------------------------------------------------------------
.remove()  works on any collection , similar to .find() method...ie unless you specify wch document to remove inside a collection it will remove all one-by-one..
 Recall the schema of the scores collection:
{
"_id" : ObjectId("50844162cb4cf4564b4694f8"),
"student" : 0,
"type" : "exam",
"score" : 75
}
Delete every document with a score of less than 60. 
 > db.scores.remove({score:{$lt:60}})
   ----------------------------------------------------------------------------------
# getLastError
 d.runCommand({getLastError:1}) --will let u know whether the last DB-Operation failed or ws successfull
   ----------------------------------------------------------------------------------