Data Analysis and MongoDB workshop I: get started

Posted on Feb 11, 2014

[Best_Wordpress_Gallery gallery_type="thumbnails" theme_id="1" gallery_id="18" sort_by="order" order_by="asc" show_search_box="0" search_box_width="180" image_column_number="5" images_per_page="30" image_title="none" image_enable_page="1" thumb_width="200" thumb_height="150" thumb_click_action="undefined" thumb_link_target="undefined" popup_fullscreen="0" popup_autoplay="0" popup_width="800" popup_height="500" popup_effect="fade" popup_interval="5" popup_enable_filmstrip="1" popup_filmstrip_height="70" popup_enable_ctrl_btn="1" popup_enable_fullscreen="1" popup_enable_info="1" popup_info_always_show="0" popup_enable_rate="0" popup_enable_comment="1" popup_hit_counter="0" popup_enable_facebook="1" popup_enable_twitter="1" popup_enable_google="1" popup_enable_pinterest="0" popup_enable_tumblr="0" watermark_type="none" watermark_link="http://web-dorado.com"]

Many thanks go to Thoughtworks NYC for providing the space!

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

Slides:

MongoDB Workshop from eagerdeveloper

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

Meetup Announcement:

This workshop could help you get familiar with MongoDB commands.

Speakers: Kannan and Roman are Data Science enthusiasts who are constantly expanding their expertise by attending technology-related meetups in New York City, and as students of online courses at Coursera and Udacity.

Kannan works as a software developer in Weitz & Luxenberg, programming in .NET, SQL Server, PHP, and MySQL. He loves machine learning, and is currently learning Python, Java, and Hadoop.

Roman has worked in marketing, data analytics and statistical modeling roles in American Express, Citicards, 1800Flowers.com, and PetCareRx.com. He currently works in Verizon Wireless.

Outline:

1. Intro: An overview of databases and MongoDB.
2. Deep dive: Walk through with examples.
3. Hack time: Instructors will go around and help people with their tasks or answer specific questions for them.

Content:

MongoDB operations: Create, Read, Update, Delete, Aggregation
MongoDB, NoSQL and Relational Databases
Administration: Replication and sharding in MongoDB

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

Other Useful Info Link:

You can find the data and source code here (https://github.com/eagerdeveloper/mongodb_workshop/) or see below.

Welcome to MongoDB workshop
ParksNYC.json is located in parksnyc-tennis folder
mongoimport to import the dataset
At the terminal, use: mongoimport -d tennis -c ParksNYC --type json --drop < ParksNYC.json
//import (to be run in mongo shell) mongoimport -d tennis -c ParksNYC --type json --drop < ParksNYC.json
//Mongo 
//show dbs
//use tennis
//show collections


//first command    
db.ParksNYC.insert(
{
    Prop_ID : "Q900",
    Name : "Ridge Park",
    Location : "1843 Norman St.",
    EstablishedOn: "1/1/1970"
})


// as in sql if you run this command twice it will create 2 documents with same details 
// read specific dacument
db.ParksNYC.find(
{Name : "Ridge Park"
})

// read all documents
db.ParksNYC.find()
// read first document 
db.ParksNYC.findOne()
// find specific document
// find specific fields in all documents
db.ParksNYC.find({ },{  Name: 1 })
db.ParksNYC.find({ },{ _id: 0, Name: 1 })
//Find documents meeting specific conditions 
db.ParksNYC.find(
   { Courts: { $gt: 5, $lte: 8} }
)
   
// regular expression
db.ParksNYC.find({ Name: /^F/ })

   
// update (insert) field conditional on other field criteria
db.ParksNYC.update({Prop_ID : /^X/ }, {$set: { "Boro":"Bronx"}},{ multi: true })
db.ParksNYC.findOne({Prop_ID : /^X/ })
// update conditional on field criteria $push
db.ParksNYC.update(
                    { Name : "Van Cortlandt Park"},
                    { $push: { Tennis_Type: "Clay" } }
                  )
                    
db.courts_b2.find({"Prop_ID" : "B129" })
  db.ParksNYC.update(
                    { Prop_ID: "B129" },
                    { $push: { Tennis_Type: "Grass" } })
                    
db.ParksNYC.find()
db.ParksNYC.find({"Name" : "Van Cortlandt Park" })                    
                    
db.ParksNYC.find({Tennis_Type: "Clay"}) 
db.ParksNYC.find({Tennis_Type: "Grass"}) 
// update
db.ParksNYC.update(
    { },
    { $set: {VisitDate: "1/1/2014" } },
    { multi: true }
)
db.ParksNYC.findOne()
    
// delete field
db.ParksNYC.update(
    { },
    { $unset: {VisitDate: "" } },
    { multi: true }
) 
   
//delete document
db.ParksNYC.remove(
{ Name:"Ridge Park"
})
// to check if doc has been removed
db.ParksNYC.find({ Name:"Ridge Park"})

// aggregation framework
// sort
db.ParksNYC.aggregate(
    { $sort : { Courts : -1, Accessible: 1 } }
)
 
// limit
db.ParksNYC.aggregate(
    { $limit : 5 }
) 
 
//skip   
    
db.ParksNYC.aggregate(
    { $skip : 70 }
)
// $group by
db.ParksNYC.aggregate(
    { $group : {
        _id : "$Accessible",
        Parks_Number : { $sum : 1 },
        Courts_Number : { $sum : "$Courts" }
    }}
)
db.ParksNYC.aggregate([ { 
    $group: { 
        _id: "$Accessible", 
        total: { 
            $sum: "$Courts" 
        } 
    } 
} ] )
//sum
db.ParksNYC.aggregate([ { 
    $group: { 
        _id: null, 
        total: { 
            $sum: "$Courts" 
        } 
    } 
} ] )
    

// unwind single document
  db.ParksNYC.find({ Name: "Mill Pond Park"}) 
  db.ParksNYC.aggregate ([
   {
      "$match":
      {
         "Name": "Mill Pond Park"
      }
   },
   {
      "$unwind": "$Tennis_Type"
   }
])
// unwind entire Tennis_Type for collection and group by park
db.ParksNYC.aggregate ([
   
   {
      "$unwind":"$Tennis_Type"
   },
   {
      "$group":
      {
         "_id":
         {
            "Name" : "$Name" 
         },
         "Surface_Type_Count":
         {
            "$sum": 1
         }
      }
   }
])
  
//unwind on tennis_type, group by parks and sort by Surface_Type_Count
db.ParksNYC.aggregate ([
   {
      "$unwind":"$Tennis_Type"
   },
   {
      "$group":
      {
         "_id":
         {
            "Name" : "$Name" 
         },
         "Surface_Type_Count":
         {
            "$sum": 1
         }
      }
   },
{
      "$sort":
      {
         "Surface_Type_Count":-1,
         "Name":1
      }
   }
])     
//$unwind on tennis_type, $group by parks , $limit to only top 6 parks, save results in new 'summary' collection  
db.ParksNYC.aggregate ([
   
   {
      "$unwind":"$Tennis_Type"
   },
   {
      "$group":
      {
         "_id":
         {
            "Name" : "$Name" 
         },
         "Surface_Type_Count":
         {
            "$sum": 1
         }
      }
   },
{
      "$sort":
      {
         "Surface_Type_Count":-1,
         "Name":1
      }
   }, 
   {
      "$limit":6,
   },
     { $out : "summary" }
])
//check
     db.summary.find()
//exportsummary to csv file
//mongoexport -d tennis -c summary --out summary.csv

About Author

Related Articles

Leave a Comment

No comments found.

View Posts by Categories


Our Recent Popular Posts


View Posts by Tags

#python #trainwithnycdsa 2019 2020 Revenue 3-points agriculture air quality airbnb airline alcohol Alex Baransky algorithm alumni Alumni Interview Alumni Reviews Alumni Spotlight alumni story Alumnus ames dataset ames housing dataset apartment rent API Application artist aws bank loans beautiful soup Best Bootcamp Best Data Science 2019 Best Data Science Bootcamp Best Data Science Bootcamp 2020 Best Ranked Big Data Book Launch Book-Signing bootcamp Bootcamp Alumni Bootcamp Prep boston safety Bundles cake recipe California Cancer Research capstone car price Career Career Day citibike classic cars classpass clustering Coding Course Demo Course Report covid 19 credit credit card crime frequency crops D3.js data data analysis Data Analyst data analytics data for tripadvisor reviews data science Data Science Academy Data Science Bootcamp Data science jobs Data Science Reviews Data Scientist Data Scientist Jobs data visualization database Deep Learning Demo Day Discount disney dplyr drug data e-commerce economy employee employee burnout employer networking environment feature engineering Finance Financial Data Science fitness studio Flask flight delay gbm Get Hired ggplot2 googleVis H20 Hadoop hallmark holiday movie happiness healthcare frauds higgs boson Hiring hiring partner events Hiring Partners hotels housing housing data housing predictions housing price hy-vee Income Industry Experts Injuries Instructor Blog Instructor Interview insurance italki Job Job Placement Jobs Jon Krohn JP Morgan Chase Kaggle Kickstarter las vegas airport lasso regression Lead Data Scienctist Lead Data Scientist leaflet league linear regression Logistic Regression machine learning Maps market matplotlib Medical Research Meet the team meetup methal health miami beach movie music Napoli NBA netflix Networking neural network Neural networks New Courses NHL nlp NYC NYC Data Science nyc data science academy NYC Open Data nyc property NYCDSA NYCDSA Alumni Online Online Bootcamp Online Training Open Data painter pandas Part-time performance phoenix pollutants Portfolio Development precision measurement prediction Prework Programming public safety PwC python Python Data Analysis python machine learning python scrapy python web scraping python webscraping Python Workshop R R Data Analysis R language R Programming R Shiny r studio R Visualization R Workshop R-bloggers random forest Ranking recommendation recommendation system regression Remote remote data science bootcamp Scrapy scrapy visualization seaborn seafood type Selenium sentiment analysis sentiment classification Shiny Shiny Dashboard Spark Special Special Summer Sports statistics streaming Student Interview Student Showcase SVM Switchup Tableau teachers team team performance TensorFlow Testimonial tf-idf Top Data Science Bootcamp Top manufacturing companies Transfers tweets twitter videos visualization wallstreet wallstreetbets web scraping Weekend Course What to expect whiskey whiskeyadvocate wildfire word cloud word2vec XGBoost yelp youtube trending ZORI