MongoDB
Introduction to MongoDB
Objective: Teach a set of basic concepts in MongoDB and Git.1. Start MongoDB instance locally by issuing the following command inside the bin folder inside MongoDB installation directory.
cd C:\ProgramFiles\MongoDB\Server\4.2\bin\
The above command will only work if you have C:\data\db folder created (assuming you have installed MongoDB in C: drive). Otherwise, you need to provide a data directory path by issuing the following command. The data directory is used by MongoDB to save all the files related to databases.
mongod --dbpath [PATH_TO_DATA_DIRECTORY]
2. Check MongoDB is working by connecting to the local instance using an IDE.Default port for MongoDB is 27017.
3. Add the following document to the database sliit;
{ "name": "John",
"dateOfBirth": "1990-01-01T00:00:00Z",
"subjects": ["Application frameworks", "Computer architecture"]
}
db.getCollection('Lab03_MongoDB').insertOne({
"name" : "john",
"name": "John",
"dateOfBirth": "1990-01-01T00:00:00Z",
"subjects": ["Application frameworks", "Computer Architecture"]
})
● We always make sure to add dates in MongoDB as a UTC date since MongoDB by default deals with UTC timezone and format.
4. Find the document by ‘name’.
db.getCollection('Lab03_MongoDB').find({
"name": "John"})
5. Find the document by ‘_id’.
db.getCollection('Lab03_MongoDB').find({
"_id":ObjectId("604a2b5a9418916e7c143978")})
6. Add ‘Distributed Computing’ to the subjects list.
db.getCollection('Lab03_MongoDB').update(
{
"name": "John"
},
{
$push:{"subjects":"Distributed Computing"}
})
7. Add the following 2 documents to the same collection.
{
"name": "Smith",
"dateOfBirth": "1990-01-15T00:00:00Z",
"subjects": ["Application frameworks", "Computer architecture"],
"isActive": true
}
{
"name": "Jane",
"dateOfBirth": "1990-02-15T00:00:00Z",
"subjects": ["Application frameworks", "Computer architecture"],
"isActive": false
}
db.getCollection('Lab03_MongoDB').insertMany([
{
"name": "Smith",
"dateOfBirth": "1990-01-15T00:00:00Z",
"subjects": ["Application frameworks", "Computer architecture"],
"isActive": true
},
{
"name": "Jane",
"dateOfBirth": "1990-02-15T00:00:00Z",
"subjects": ["Application frameworks", "Computer architecture"],
"isActive": false
}
])
8. Find the document with the name ‘Smith’ and isActive flag is true and add Distributed computing to subjects.
db.getCollection('Lab03_MongoDB').update(
{
"name": "Smith",
"isActive" : {$eq:true}
},
{
$push:{"subjects":"Distributed Computing"}
})
db.getCollection('Lab03_MongoDB').update(
{"name":"John"},
{$push:{"isActive":false}}
)
10. Remove the first document created
db.getCollection('Lab03_MongoDB').deleteOne(
{"name":"John"}
)
11. Find all data
db.getCollection('Lab03_MongoDB').find({ })
Comments
Post a Comment