1. Running mongoDB server in a particular port
By default mongoDB runs on the port 27017 on local machine. To run it on a different port in local machine the following commands are used
- Running mongoDB server
mongod --port 27018
- Running mongoDB shell
mongo --port 27018
2. Database, Collection and Documents
One or more database can exists.
Inside one database
there are several Collections
. Inside one collection
there are several Documents
(or piece of data)
>use flights
switched to db flights
>show dbs
admin
config
local
Until we insert data flights
will not be shown by use dbs
.
Database, collection will be created only when we start inserting data.
3. JSON, BSON and _id
MongoDB actually stores BSON data. It happens behind the scene and we don't have to worry about this.
db.book.insertOne({ "name": "A book" })
is same asdb.book.insertOne({ name: "A book" })
which is also same asdb.book.insertOne({ 'name': "A book" })
.
name
is not quoted in the second case, we can do it as long as there is not white space in the key._id
is inserted by mongoDB. This is unique for every entry. ObjectId() also includes timestamp inside it. So a sorting by time is guaranteed using ObjectId.We can also manually insert _id. But in that case it have to be unique. Otherwise we'll get a duplicate key error.
4. CRUD Intro
CREATE
insertOne(data, options)
insertMany(data, options)
READ
find(filter, options)
findOne(filter, options)
find
returns all the matches and findOne
returns only the first match.
DELETE
deleteOne(filter, options)
deleteMany(filter, options)
UPDATE
updateOne(filter, data, options)
updateMany(filter, data, options)
repaceOne(filter, data, options)
Example
>db.flightData.find().pretty()
{
"_id" : ObjectId("5fa6408a74dbf85f087ac5c4"),
"departureAirport" : "MUC",
"arrivalAirport" : "SFO",
"aircraft" : "Airbus A380",
"distance" : 12000,
"intercontinental" : true
}
{
"_id" : ObjectId("5fa6433574dbf85f087ac5c5"),
"departureAirport" : "Kol",
"arrivalAirport" : "Delhi"
}
{
"_id" : "kol-delhi-1",
"departureAirport" : "Kol",
"arrivalAirport" : "Delhi"
}
db.flightData.deleteOne({ _id: "kol-delhi-2" })
will not return any error.
db.flightData.deleteOne({ _id: "kol-delhi-1" })
will delete the last entry.
db.flightData.deleteMany({})
will delete all of the entries as {}
selects every entry.
db.flightData.updateOne({ distance: 12000 } , { distance: 1000 })
will not work and will return an error. We've to use $set
keyword here.
db.flightData.updateOne({distance: 12000 }, {$set: { distance: 1000}})
will actually update the first match.
5. Understanding insertMany()
We've to pass an array to insertMany()
like this: insertMany([ {...}, {...} ])
example:
db.flightData.insertMany([
{
"departureAirport": "MUC",
"arrivalAirport": "SFO",
},
{
"departureAirport": "LHR",
"aircraft": "Airbus A320",
}
])
6. Diving deeper into find
data
To find exactly equal to something: db.flightData.find({ distance: 12000 })
To find greater than a distance db.flightData.find({ distance: {$gt: 10000} })
To find less than a distance db.flightData.find({ distance: {$lt: 10000} })
.find()
returns all of the matches whereas .findOne()
returns only the first match.
7. update
, updateOne
and updateMany
update
replaces the whole object where updateMany
and updateOne
adds attributes to the existing object and not overwrites.
Instead update
, it is better to use replaceOne
function.
The syntax of update
is db.passengers.update({_id:"ps1"}, {key:value})
. It does not contain $set
keyword.
8. Understanding the find() and the cursor object
.find()
returns only the first 20 results, it actually returns a cursor. To get all of the data we've to use db.passengers.find().toArray()
In mongoDB shell we can use forEach()
to the query and it fetches data one by one and not all the data at once.
db.passengers.find().forEach()
pretty()
can be applied only on the cursor object and that's why we can apply pretty()
only to the .find()
method and not the others like findOne()
etc.
9. Understanding Projection
Selecting the columns is called projection.
{
"_id" : ObjectId("5fa7a7930a15db273b6746aa"),
"name" :"Armin Glutch",
"age" : 35
}
We've a lot of objects like above. To select only the name we can do the following db.passengers.find({}, { name:1})
. Note that the first object is empty, which means select all of the objects and then select only the 'name' attribute.
_id
is selected by default. To off the _id also, we can write the following db.passengers.find({}, {_id:0, name:1})
10. Embedded Documents
Documents inside a document. Till 100 level is permissible in mongoDB and the size of a document can be maximum of 16MB.
An example of inserting embedded document:
db.flightData.updateMany({}, {$set: {status: {delayed:"on-time", "last-update":"1 hr ago", pilots:{name:"Rittwick"}}}})
An example of inserting embedded array:
db.passengers.updateMany({age:35}, {$set: hobbies:["coocking", 'sports']})
Retrieving embedded document:
db.flightData.find({"status.delayed":"on-time"}).pretty()
Note that status.delayed
is under quotes. We've to use quote otherwise it will not work.
Retrieving embedded array:
db.passengers.findOne({age:35}).hobbies
11. Wrap Up
Database, Collection and Documents
- A Database can hold multiple document, and a document can hold multiple document.
- Database and collections are created lazily, i.e. when a document is inserted.
- A Document can't directly be inserted in a database, you need to use a collection. Document Structure
- Each document needs a unique id (and gets a by default).
- You may have embedded array and document fields. CRUD Operations
- CRUD = Create, Read, Update, Delete
- find() returns a cursor, NOT a list of documents.
Top comments (0)