SlideShare a Scribd company logo
1 of 12
ObjectID in MongoDB
                            Tips & tricks



                                            Vlad ZLOTEANU
     #ParisRB                    Software Engineer @ Dimelo
     Nov 12, 2012
                                              @vladzloteanu


Copyright Dimelo SA                                www.dimelo.com
Poll


           How many:

                 Using mongo in prod

                 Using mongo on personal projects

                 Interested in mongo

                 What’s “moun-gooh?”

Copyright Dimelo SA                                 www.dimelo.com
ObjectID – facts


           any (mongo) document has an _id attribute
              (exception: capped collections, system
              collections)

           immutable

           generated automatically by DB if none is provided




Copyright Dimelo SA                                    www.dimelo.com
ObjectID – interesting facts


     it is usually a BSON ObjectID
          but it can be any object (except for: arrays), as
          long as it's unique

     it is usually generated by the driver (on client side)

     each collection has a unique index on ObjectID

  class Model ; include Mongoid::Document ; end

    Model.new.id
        # => 50a13e6a29a86ea0ff000002
Copyright Dimelo SA                                  www.dimelo.com
BSON ObjectID



                      0   1   2   3   4   5   6   7   8   9 10 11

                          Time        Machine     Pid       Inc


           Time: Unix timestamp (sec)
           Machine: md5 hash of machine name
           Pid
           Inc: incrementing value starting with a random
           number
Copyright Dimelo SA                                               www.dimelo.com
?



        relational DB: sequence numbers (incremental) as
      ID, generated by DB

        mongoDB: pseudo-incremental objects, not in
      sequence, generated client-side

          Any reason?

                         #parisrb
                                     #whymranderson
Copyright Dimelo SA                                www.dimelo.com
Tip: extract generation time


           granularity: 1s
           optimize space  no more need for created_at field

    bson_id = Model.last.id

    bson_id.generation_time
      # => 2012-11-12 15:23:45 UTC




Copyright Dimelo SA                                  www.dimelo.com
Tip: range query by date


           ! granularity: 1s

            no more need for index on created_at

    first_object_id =
    Moped::BSON::ObjectId.from_time(1.day.ago)
        # => "509fc3d20000000000000000”


    Model.where(:_id.gte => first_object_id).count
     # => 1
Copyright Dimelo SA                                  www.dimelo.com
Tip: sort by date


           ! 1s precision search (cvasi-inconsistent order)

           no more need for index on created_at

    Model.asc(:_id)
     # instead of: Model.asc(:created_at)




Copyright Dimelo SA                                      www.dimelo.com
Tip: ObjectID as compound index


      Stats scenario: count hits, per page, per hour


  {
       _id: "{day}/{page}", # “20120108/index”
       hour: {
           1: 200
           2: 149
           …
           24: 455
       }
      total: 2344
    }
Copyright Dimelo SA                                www.dimelo.com
Tip: compound index [2]


           only one upsert (in-place change) using default
           index, no need for extra index

    # new hit arrives

    conditions = {:_id => "#{hit.day}/#{hit.hour}"}

    Stat.collection.find(conditions).upsert({
      "$inc" => {"hour.#{hour}" => 1, "total" => 1}})



Copyright Dimelo SA                                     www.dimelo.com
Thank you!




Copyright Dimelo SA     www.dimelo.com

More Related Content

Similar to ObjectId in Mongodb

Introduction To Dojo
Introduction To DojoIntroduction To Dojo
Introduction To Dojo
yoavrubin
 
Data Mining Open Ap Is
Data Mining Open Ap IsData Mining Open Ap Is
Data Mining Open Ap Is
oscon2007
 

Similar to ObjectId in Mongodb (20)

Building your first app with MongoDB
Building your first app with MongoDBBuilding your first app with MongoDB
Building your first app with MongoDB
 
Java Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDBJava Persistence Frameworks for MongoDB
Java Persistence Frameworks for MongoDB
 
Clean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflixClean pragmatic architecture @ devflix
Clean pragmatic architecture @ devflix
 
DDD for real
DDD for realDDD for real
DDD for real
 
Elastic @ Adobe: Making Search Smarter with Machine Learning at Scale
Elastic @ Adobe: Making Search Smarter with Machine Learning at ScaleElastic @ Adobe: Making Search Smarter with Machine Learning at Scale
Elastic @ Adobe: Making Search Smarter with Machine Learning at Scale
 
Tokens and Complex Systems
Tokens and Complex SystemsTokens and Complex Systems
Tokens and Complex Systems
 
Flying a Drone with JavaScript and Computer Vision
Flying a Drone with JavaScript and Computer VisionFlying a Drone with JavaScript and Computer Vision
Flying a Drone with JavaScript and Computer Vision
 
Content Mangement Systems and MongoDB
Content Mangement Systems and MongoDBContent Mangement Systems and MongoDB
Content Mangement Systems and MongoDB
 
IndexedDB and Push Notifications in Progressive Web Apps
IndexedDB and Push Notifications in Progressive Web AppsIndexedDB and Push Notifications in Progressive Web Apps
IndexedDB and Push Notifications in Progressive Web Apps
 
DDD, CQRS & ES lessons learned (Gitte Vermeiren)
DDD, CQRS & ES lessons learned (Gitte Vermeiren)DDD, CQRS & ES lessons learned (Gitte Vermeiren)
DDD, CQRS & ES lessons learned (Gitte Vermeiren)
 
moma-django overview --> Django + MongoDB: building a custom ORM layer
moma-django overview --> Django + MongoDB: building a custom ORM layermoma-django overview --> Django + MongoDB: building a custom ORM layer
moma-django overview --> Django + MongoDB: building a custom ORM layer
 
Introduction To Dojo
Introduction To DojoIntroduction To Dojo
Introduction To Dojo
 
Data Mining Open Ap Is
Data Mining Open Ap IsData Mining Open Ap Is
Data Mining Open Ap Is
 
MongoDB .local Paris 2020: Les bonnes pratiques pour travailler avec les donn...
MongoDB .local Paris 2020: Les bonnes pratiques pour travailler avec les donn...MongoDB .local Paris 2020: Les bonnes pratiques pour travailler avec les donn...
MongoDB .local Paris 2020: Les bonnes pratiques pour travailler avec les donn...
 
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB AtlasMongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
MongoDB SoCal 2020: Migrate Anything* to MongoDB Atlas
 
Tic tac toe with IBM DevOps
Tic tac toe with IBM DevOpsTic tac toe with IBM DevOps
Tic tac toe with IBM DevOps
 
The Art of Clean code
The Art of Clean codeThe Art of Clean code
The Art of Clean code
 
Green dao
Green daoGreen dao
Green dao
 
MongoDB for Developers
MongoDB for DevelopersMongoDB for Developers
MongoDB for Developers
 
Plone pwns
Plone pwnsPlone pwns
Plone pwns
 

Recently uploaded

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
WSO2
 

Recently uploaded (20)

MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Architecting Cloud Native Applications
Architecting Cloud Native ApplicationsArchitecting Cloud Native Applications
Architecting Cloud Native Applications
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 

ObjectId in Mongodb

  • 1. ObjectID in MongoDB Tips & tricks Vlad ZLOTEANU #ParisRB Software Engineer @ Dimelo Nov 12, 2012 @vladzloteanu Copyright Dimelo SA www.dimelo.com
  • 2. Poll How many: Using mongo in prod Using mongo on personal projects Interested in mongo What’s “moun-gooh?” Copyright Dimelo SA www.dimelo.com
  • 3. ObjectID – facts any (mongo) document has an _id attribute (exception: capped collections, system collections) immutable generated automatically by DB if none is provided Copyright Dimelo SA www.dimelo.com
  • 4. ObjectID – interesting facts it is usually a BSON ObjectID but it can be any object (except for: arrays), as long as it's unique it is usually generated by the driver (on client side) each collection has a unique index on ObjectID class Model ; include Mongoid::Document ; end Model.new.id # => 50a13e6a29a86ea0ff000002 Copyright Dimelo SA www.dimelo.com
  • 5. BSON ObjectID 0 1 2 3 4 5 6 7 8 9 10 11 Time Machine Pid Inc Time: Unix timestamp (sec) Machine: md5 hash of machine name Pid Inc: incrementing value starting with a random number Copyright Dimelo SA www.dimelo.com
  • 6. ? relational DB: sequence numbers (incremental) as ID, generated by DB mongoDB: pseudo-incremental objects, not in sequence, generated client-side Any reason? #parisrb #whymranderson Copyright Dimelo SA www.dimelo.com
  • 7. Tip: extract generation time granularity: 1s optimize space  no more need for created_at field bson_id = Model.last.id bson_id.generation_time # => 2012-11-12 15:23:45 UTC Copyright Dimelo SA www.dimelo.com
  • 8. Tip: range query by date ! granularity: 1s  no more need for index on created_at first_object_id = Moped::BSON::ObjectId.from_time(1.day.ago) # => "509fc3d20000000000000000” Model.where(:_id.gte => first_object_id).count # => 1 Copyright Dimelo SA www.dimelo.com
  • 9. Tip: sort by date ! 1s precision search (cvasi-inconsistent order) no more need for index on created_at Model.asc(:_id) # instead of: Model.asc(:created_at) Copyright Dimelo SA www.dimelo.com
  • 10. Tip: ObjectID as compound index Stats scenario: count hits, per page, per hour { _id: "{day}/{page}", # “20120108/index” hour: { 1: 200 2: 149 … 24: 455 } total: 2344 } Copyright Dimelo SA www.dimelo.com
  • 11. Tip: compound index [2] only one upsert (in-place change) using default index, no need for extra index # new hit arrives conditions = {:_id => "#{hit.day}/#{hit.hour}"} Stat.collection.find(conditions).upsert({ "$inc" => {"hour.#{hour}" => 1, "total" => 1}}) Copyright Dimelo SA www.dimelo.com
  • 12. Thank you! Copyright Dimelo SA www.dimelo.com