MongoDB_Ex
MongoDB_Ex
Instillations
o https://www.mongodb.com/download-center/community
2. Download and Install MongoDB community server
o Create a separate installation location/directory “mongodb” (for windows, c:\mongodb) and install
your MongoDB in that location instead of default location. (this will be helpful later when you are
starting the service)
o Start custom installation option
o Uncheck “Install MongoD as a Service” option and hit next.
3. Create 3 folders inside mongodb after installations
o Create a folder “data” c:\mongodb\data
Create a folder “db” inside data folder created above. c:\mongodb\data\db
o Create a folder “log” c:\mongodb\log
4. Use Command Interpreter (cmd for windows, open with admin privilege)
o Change the path from command line to where you have your mongoDB\bin folder
o Now type
mongod –directoryperdb –dbpath c:\mongodb\data\db –logpath c:\mongodb\log\mongo.log
–logappend –install
5. Start the MongoDB service.
o Type of the followings
net start MongoDB
______________________________________________________________
1. Start MongoDB
o type mongo to start mongo shell
o Cls to clear the screen
MongoDB stores BSON documents, i.e. data records, in collections; the collections in databases.
BSON is a binary representation of JSON documents
Database is a physical container for collections.
Collection is a group of MongoDB documents. It is the equivalent of an RDBMS table. A
collection exists within a single database. Collections do not enforce a schema. Documents within
a collection can have different fields. Typically, all documents in a collection are of similar or
related purpose.
9. [Exercise] use an array to insert following to a database "petshop" and collection "pets"
o Add another piranha called Pete, and a naked mole rat called Henry.
o Use find to list all the pets. Find the ID of Mikey the Gerbil.
o Use find to find all the gerbils.
o Find all the creatures named Mikey.
o Find all the creatures named Mikey who are gerbils.
o Find all the creatures with the string "dog" in their species
10. Update
o db.customers.update({first_name:"Sam"}, {first_name:"Sam", last_name:"Smith",
gender:"male"})
o You need to repeat all the fields with their data. Otherwise document will replace by just the fields
available in the update statement. Use the $set operator instead.
11. Remove
o db.customers.remove( {}) // remove all the documents
o db.customers.remove( {first_name:"Sam"}, {justone: true})
o justone will delete only first document it finds, otherwise it will delete all
12. Import
o Import json files to the database
o Exit from the mongo: type "exit" and then type the following in the command line. Your
path should still be mongodb\bin
[Exercise] First download the file from and save it somewhere
https://www.cs.odu.edu/~sampath/courses/f19/cs620/files/data/stocks.json
mongoimport --db stocks --collection stocks --file stocks.json