b¬äd†ødd

Dedicated to design and performance of databases and audio systems.

MongoDB Shell Starter Kit

Overall:

mongo ← the MongoDB client / shell
mongod ← the MongoDB database server

MongoDB is a non-relational / NoSQL database

  • There is no SQL → all access is via application drivers or the shell
  • There are no collection (table) joins in MongoDB

While administrators will use the shell for access to the databases, most access to the data will occur via application drivers (e.g. Java, Python, Ruby).


MongoDB object hierarchy:

  • database
    • collection (table in the relational world)
      • document (record in the relational world)

MongoDB reference


Shell:

  • uses Javascript

MongoDB reference


Database:

db → show the current assigned database

use foo

  • change the current database to foo
  • if foo does not exist, it is created
the db alias is now assigned the database specified with use

show dbs → list the databases present and populated

show collections → list collections (tables) within the current database

MongoDB reference


Create:

use foo → creates database foo if foo does not yet exist

db.createCollection("olympics") → explicitly creates the collection olympics

MongoDB reference

db.olympics.insert( { } ) → implicitly creates the collection olympics if it does not already exist, and will insert a document into the olympics collection

MongoDB reference


Insert:

  • _id field value can be explicitly specified, or omitted for a default value
  • the _id field can be of any data type, but must be unique

the default value for _id is a 12-byte ObjectID value consisting of

  • Seconds since the epoch (i.e. 1970-01-01): 4 bytes
  • Machine ID: 3 bytes
  • PID (process ID): 2 bytes
  • Increment: 3 bytes

db.olympics.insert( {
    _id : NumberInt(1),
    name : "I",
    year : NumberInt(1924),
    location : {
        city : "Chamonix",
        country: "France"
    },
    period : {
        start : ISODate("1924-01-25"),
        end : ISODate("1924-02-05")
    },
    nations : NumberInt(16),
    competitors : {
        total : NumberInt(258),
        men : NumberInt(247),
        women : NumberInt(11)
    },
    sports : NumberInt(6),
    disciplines : NumberInt(9),
    events : NumberInt(16)
} )

documents may have differing field sets relative to others in the same collection

db.olympics.insert( {
    _id : NumberInt(23),
    name : "XXIII",
    year : NumberInt(2018),
    location : {
        city : "Pyeongchang",
        country: "South Korea"
    },
    period : {
        start : ISODate("2018-02-09"),
        end : ISODate("2018-02-25")
    }
} )

documents may be updated in batch, as an array

db.olympics.insert( [ 
{
    _id : NumberInt(2),
    name : "II",
    year : NumberInt(1928),
    location : {
        city : "St. Mortiz",
        country: "Switzerland"
    },
    period : {
        start : ISODate("1928-02-11"),
        end : ISODate("1928-02-19")
    },
    nations : NumberInt(25),
    competitors : {
        total : NumberInt(464),
        men : NumberInt(438),
        women : NumberInt(26)
    },
    sports : NumberInt(4),
    disciplines : NumberInt(8),
    events : NumberInt(14)
}
,
{
    _id : NumberInt(3),
    name : "III",
    year : NumberInt(1932),
    location : {
        city : "Lake Placid",
        country: "United States"
    },
    period : {
        start : ISODate("1932-02-04"),
        end : ISODate("1932-02-15")
    },
    nations : NumberInt(17),
    competitors : {
        total : NumberInt(252),
        men : NumberInt(231),
        women : NumberInt(21)
    },
    sports : NumberInt(4),
    disciplines : NumberInt(7),
    events : NumberInt(14)
} 
] )

MongoDB reference

or saved (if keyed it overwrites an existing document)

db.olympics.save( {
    _id : NumberInt(4),
    name : "IV",
    year : NumberInt(1936),
    location : {
        city : "Garmisch-Partenkirchen",
        country: "Germany"
    },
    period : {
        start : ISODate("1936-02-06"),
        end : ISODate("1936-02-16")
    },
    nations : NumberInt(28),
    competitors : {
        total : NumberInt(646),
        men : NumberInt(566),
        women : NumberInt(80)
    },
    sports : NumberInt(4),
    disciplines : NumberInt(8),
    events : NumberInt(17)
} )

MongoDB reference

documents can be generated

for (var i = 25; i < 30; i++) {
    db.olympics.insert({ "_id" : i, "name" : "" } )
}

a file of JSON-formatted data to specified target databases and collections

./mongoimport --db foo --collection olympics --file games.json

MongoDB


Read:

query all records:

  • relational world SQL → select * from olympics;
  • MongoDB → db.olympics.find()

formatting for readability:

  • db.olympics.find().pretty()

select one document (record):

  • db.olympics.findOne()
  • db.olympics.find().limit(1)

MongoDB reference

apply criteria:

  • SQL → select * from olympics where name = 'I';
  • MongoDB → db.olympics.find( { "name" : "I" } )

restrict projection (select):

  • SQL → select name from olympics where ID = 12;
  • MongoDB → db.olympics.find({"_id" : 12},{"name" : 1, "_id" : 0})

the _id field will project by default unless explicitly restricted

MongoDB reference

sub-document search:

  • SQL → select * from olympics where city = 'Oslo';
  • MongoDB → db.olympics.find( { "location.city" : "Oslo"} )

MongoDB reference


Update:

MongoDB →

  • update the number of Sochi events from 98 to 99 via $set
  • db.olympics.update( { _id : 22 },{ $set : { "events" : 99 } } )

MongoDB reference

  • reset the number of events back to 98 via $inc
  • db.olympics.update( { _id : 22 },{ $inc : { "events" : -1 } } )

MongoDB reference

Will the 2022 Winter games be in Oslo, Norway?

db.olympics.insert( {
    _id : NumberInt(24),
    name : "XXIIII", 
    year : NumberInt(2022),
    location : {
        city : "Oslo",
        country : "Norway"
    }
} )

Or, Krakow, Poland?

db.olympics.save( {
    _id : NumberInt(24),
    name : "XXIIII", 
    year : NumberInt(2022),
    location : {
        city : "Krakow",
        country : "Poland"
    }
} )

MongoDB reference

Change the Roman numerals of the 24th Winter Olympiad from XXIIII to XXIV:

db.olympics.update( { _id: 24 },{ $set : { name : "XXIV" } } )

Add the name field with a default N/A value to the 1944 Olympics:

db.olympics.findAndModify( {
    query : { year : 1944 },
    update : { $set : { name : "N/A" } }
} )

Note: findAndModify atomically modifies and returns a single document.

MongoDB reference

Add an array of the 1924 disciplines:

db.olympics.update( 
    { year : 1924 },
    { $push :
        { discipline :
            { $each : [
                "Bobsleigh",
                "Cross-country skiing",
                "Curling",
                "Figure skating",
                "Ice hockey",
                "Nordic combined",
                "Ski jumping",
                "Speed skating" 
                ]
            }
        }
    }
)

MongoDB reference


Delete:

drop database:

db.dropDatabase()

MongoDB reference

drop collection:

db.olympics.drop()

MongoDB reference

truncate collection:

db.coll.remove( { } )

delete document:

db.olympics.remove(
    { celebrated : false },
    { justOne : false }
)

MongoDB reference