Friends, After MongoDB basic overview and system setup now let’s discuss some basic CRUD operations on MongoDB.
First start MongoDB service which we installed in previous article using below command. You can change the db and log path as per your convenience –
Step-1 : Install service
>mongod –dbpath D:\MongoDbFiles\data –logpath “D:\MongoDbFiles\logs\mongo.logs” –logappend –install –serviceName mdb27017 –serviceDisplayName “MongoDB Server Instance 27017” -serviceDescription “MongoDB Server Instance running on 27017”
Step-2 : Start Service
>net start mdb27017
Step-3 : Start mongo client/shell
>mongo OR mongo.exe
As we have three things in MongoDB which are Database, Collection and Document. So lets do some CRUD operation on these.
CRUD Operations on Database (In MongoDB, databases hold collections of documents) –
- Create => use DATABASE_NAME command will create a new database if it doesn’t exist, otherwise it will switch to the existing database.
- > use TestDB
- switched to db TestDB
- Read => db command is use to display current database name and show dbs use to display all database names. If a database database does not have any record then it will not display in the list.
- > db
- TestDB
- > show dbs
- admin 0.00 GB
local 0.00 GB
- Update => We have two options to rename a database. First, copy database with the new name using db.copyDatabase() method and second is create a backup of database using mongodump utility program and restore with a new name using mongorestore utility and then delete the old database. Make sure that new database is created before deleting old database.
- Rename with Database Copy
- > db.copyDatabase(‘old_database_name’, ‘new_database_name’)
- { “ok” : 1 }
- Rename with Backup/Restore
- Backup => mongodump is a utility for creating a binary export of the contents of a database. Since its a program not command so we have to run it from the system command prompt, not the mongo shell.
- > mongodump –db TestDB
- Restore => mongorestore program writes data from a binary database dump created by mongodump to a MongoDB instance. Since its also a program not command so we have to run it from the system command prompt, not the mongo shell.
- > mongorestore –db NewTestDatabase ./dump/TestDB
- Rename with Database Copy
- Delete => db.dropDatabase() is used to drop the current database.
- > db.dropDatabase()
- { “dropped” : “TestDB”, “ok” : 1 }
CRUD Operations on MongoDB Collections (Collections are analogous to tables in relational databases and stores documents)-
- Create – There are two ways to create collections-
- Implicit Creation – MongoDB also creates the collection when you first store data for that collection i.e If the collection does not exist, insert operations will create the collection automaticaly.
- > db.myNewCollection.insertOne({A:10})
- {
“acknowledged” : true,
“insertedId” : ObjectId(“59b82dae3deeaa1a93747b62”)
} - > db.myNewCollection2.createIndex({B:10})
- {
“createdCollectionAutomatically” : true,
“numIndexesBefore” : 1,
“numIndexesAfter” : 2,
“ok” : 1
}
- > db.myNewCollection.insertOne({A:10})
- Explicit Creation –
- MongoDB provides the
db.createCollection()
method to explicitly create a collection with various options, such as setting the maximum size or the documentation validation rules. - > db.createCollection(“myExplicitCollection2”, { capped : true, size : 6142800, max : 10000 } )
- { “ok” : 1 }
- MongoDB provides the
- Implicit Creation – MongoDB also creates the collection when you first store data for that collection i.e If the collection does not exist, insert operations will create the collection automaticaly.
- Read – show command is used to display all available collections
- > show collections
- impCollection
myExplicitCollection
- > show collections
- Update – db.COLLECTION_NAME.renameCollection(target, dropTarget) is use to update the collection name
- > db.myNewCollection.renameCollection(“myNewRenamedCollection”, true)
- { “ok” : 1 }
- Delete – db.COLLECTION_NAME.drop() is use to delete a collection
- > db.myNewCollection.drop()
- true
CRUD Operations on MongoDB Documents (MongoDB documents is a set of key-value pairs and basic unit of data LIKE row in the RDBMS) –
- Create – Below are some methods to create documents
- db.COLLECTION_NAME.insert(<document or array of documents>) – It allows you to insert One or more documents in the collection and Returns a
WriteResult
object- > db.testCollection.insert({a:10})
WriteResult({ “nInserted” : 1 })
- In the inserted document, if we don’t specify the _id parameter, then MongoDB assigns a unique ObjectId for this document
- deprecated in major driver
- > db.testCollection.insert({a:10})
- db.COLLECTION_NAME.insertOne(document) – It allows you to insert exactly 1 document in the collection and returns the document.
- > db.testCollection.insertOne({ _id: 10, name: “jogendra”})
{ “acknowledged” : true, “insertedId” : 10 }
- > db.testCollection.insertOne({ _id: 10, name: “jogendra”})
- db.COLLECTION_NAME.insertMany() – It allows you to insert an array of documents in the collection
- > db.testCollection.insertMany([{ _id: 1, name: “jogendra”},{name: “anmol”}])
- {
“acknowledged” : true,
“insertedIds” : [
1,
ObjectId(“59b97fbf6edbc77428869950”)
]
}
- db.COLLECTION_NAME.save()
- > db.testCollection.save({ name :”sahib”, age : 4.5})
- db.COLLECTION_NAME.insert(<document or array of documents>) – It allows you to insert One or more documents in the collection and Returns a
- Read –
- Select All Documents in a Collection.
- >db.COLLECTION_NAME.find(query, projection)
- query – Optional. Specifies selection filter
- projection – Optional. Specifies the fields to return in the documents that match the query filter. To return all fields in the matching documents, omit this parameter
- >db.testCollection.find({}) OR db.testCollection.find()
{ “_id” : 1, “name” : “jogendra”, “age” : 30 }
{ “_id” : 2, “name” : “anmol”, “age” : 5 }
{ “_id” : 3, “name” : “bani”, “age” : 5 } - To display the results in a formatted way, you can use pretty() method
- >db.COLLECTION_NAME.find(query, projection)
- Return only Selected Fields- We need to pass in the second parameter i.e projection for required fields only. _id fields always returns if not explicitly excluded.
- db.testCollection.find({ age : 5}, {_id:false, name : true})
- { “name” : “anmol” }
{ “name” : “bani” }
- Select one document in a Collection
- db.COLLECTION_NAME.findOne(query, projection)
- Without query returns the first document from the collection
- db.testCollection.findOne()
- { “_id” : 1, “name” : “jogendra”, “age” : 30 }
- With a Query Specification returns the first matching document from the bios collection.
- db.testCollection.findOne({age:5})
- { “_id” : 2, “name” : “anmol”, “age” : 5 }
- db.testCollection.findOne({age:5})
- Without query returns the first document from the collection
- db.COLLECTION_NAME.findOne(query, projection)
- RDBMS Where Clause Equivalents in MongoDB – All operations are on below documents-
{ “_id” : 1, “name” : “jogendra”, “age” : 30 }
{ “_id” : 2, “name” : “anmol”, “age” : 5 }
{ “_id” : 3, “name” : “bani”, “age” : 5 }- Equality (=)
- Syntax- {:}
- Ex- Select all documents where age=5
- > db.testCollection.find({age:5})
- { “_id” : 2, “name” : “anmol”, “age” : 5 }
{ “_id” : 3, “name” : “bani”, “age” : 5 }
- Less Than (<)
- Syntax- {:{$lt:}}
- Ex- Select all documents where age < 5
- > db.testCollection.find({age:{$lt:50}})
- { “_id” : 1, “name” : “jogendra”, “age” : 30 }
{ “_id” : 2, “name” : “anmol”, “age” : 5 }
{ “_id” : 3, “name” : “bani”, “age” : 5 }
- Less Than Equals (<=)
- Syntax- {:{$lte:}}
- > db.testCollection.find({age:{$lte:5}})
- { “_id” : 2, “name” : “anmol”, “age” : 5 }
{ “_id” : 3, “name” : “bani”, “age” : 5 }
- Greater Than ( > )
- Syntax – {:{$gt:}}
- > db.testCollection.find({age:{$gt:5}})
- “_id” : 1, “name” : “jogendra”, “age” : 30 }
- Greater Than Equals ( >= )
- Syntax – {:{$gte:}}
- > db.testCollection.find({age:{$gte:30}})
- { “_id” : 1, “name” : “jogendra”, “age” : 30 }
- Not Equals ( != )
- Syntax – {:{$ne:}}
- db.testCollection.find({age:{$ne:30}})
- { “_id” : 2, “name” : “anmol”, “age” : 5 }
{ “_id” : 3, “name” : “bani”, “age” : 5 }
- Like (%text%)
- name like ‘%o%’ => contains [ / o /]
- > db.testCollection.find({name : /o/})
- name like ‘j%’ => start with [ / ^ J / ]
- > db.testCollection.find({name : / ^j /})
- name like ‘%j’ => end with [ / i $/ ]
- > db.testCollection.find({name : /i$/})
- name like ‘%o%’ => contains [ / o /]
- Equality (=)
- AND in MongoDB ($and )- In the find() method, if you pass multiple keys in a array then MongoDB treats it as AND condition
- Syntax – >
db.testCollection.find( { $and: [ {key1: value1}, {key2:value2}] }) - > db.testCollection.find({$and : [{age:5}, {name:”anmol”}]})
- { “_id” : 2, “name” : “anmol”, “age” : 5 }
- Syntax – >
- OR in MongoDB ( $or )
- db.testCollection.find( { $or: [ {key1: value1}, {key2:value2}] })
- > db.testCollection.find({ $or : [{age:30}, {name : “anmol” }]})
- { “_id” : 1, “name” : “jogendra”, “age” : 30 }
{ “_id” : 2, “name” : “anmol”, “age” : 5 }
- Using AND and OR Together
- Ex- where age <= 50 AND (name = “Jogendra” OR name = “bani”)
- > db.testCollection.find({ age:{$lte:50}, $or:[{name :”jogendra”} , {name : “bani” }]})
- { “_id” : 1, “name” : “jogendra”, “age” : 30 }
{ “_id” : 3, “name” : “bani”, “age” : 5 }
- Select All Documents in a Collection.
- Update –
- Update a Single Document-
- db.collection.updateOne(filter, update, options)
- Updates a single document within the collection based on the filter.
- > db.testCollection.updateOne({_id:1}, {$set: {name:”Jogendra Singh”, age : 31}})
- { “acknowledged” : true, “matchedCount” : 1, “modifiedCount” : 1 }
- > db.testCollection.updateOne({_id:1}, {$set: {name:”Jogendra Singh”, age : 31}, $currentDate: { lastModified: true }})
- { “_id” : 1, “name” : “Jogendra Singh”, “age” : 31, “lastModified” : ISODate(“2017-09-14T19:16:31.167Z”) }
-
$set
– to update the value of the field $currentDate
– to update the value of thelastModified
field to the current date
db.collection.update(query, update, options)
- Either updates or replaces a single document that match a specified filter or updates all documents that match a specified filter.
- db.collection.updateOne(filter, update, options)
- Update Multiple Documents
- db.collection.updateMany(filter, update, options)
- Updates multiple documents within the collection based on the filter.
- db.testCollection.updateMany({ $or: [{name:”bani”},{name : “anmol”}]}, { $set : {class: “LKG”}})
- { “_id” : 2, “name” : “anmol”, “age” : 5, “class” : “LKG” }
{ “_id” : 3, “name” : “bani”, “age” : 5, “class” : “LKG” } - db.testCollection.updateMany({ age : {$lt: 30} }, { $set : {city : “Delhi”} })
- { “_id” : 2, “name” : “anmol”, “age” : 5, “class” : “LKG”, “city” : “Delhi” }
{ “_id” : 3, “name” : “bani”, “age” : 5, “class” : “LKG”, “city” : “Delhi” }
- db.collection.updateMany(filter, update, options)
- Replace a Document
- db.collection.replaceOne(filter, replacement, options)
- Replaces a single document within the collection based on the filter.
- To replace the entire content of a document except for the
_id
field, pass an entirely new document as the second argument todb.collection.replaceOne()
- db.testCollection.replaceOne({“_id” : 3}, { firstname : “Gurbani”, lastname : “kaur”, age : 2.5})
- { “_id” : 3, “firstname” : “Gurbani”, “lastname” : “kaur”, “age” : 2.5 }
- db.collection.replaceOne(filter, replacement, options)
- Rename field name
- $rename
- The
$rename
operator updates the name of a field - db.testCollection.update({“_id”: 3}, {$rename : {firstname : “First-Name”}})
- { “_id” : 3, “lastname” : “kaur”, “age” : 2.5, “First-Name” : “Gurbani” }
- The
- $rename
- Update a Single Document-
- Delete –
- db.collection.remove()
- Removes documents from a collection.
- he
db.collection.remove()
method can have one of two syntaxes. Theremove()
method can take a query document and an optionaljustOne
boolean. - >db.testCollection.remove({“_id” : ObjectId(“59b992326edbc77428869952”)})
- db.collection.deleteOne(filter, { writeConcern: , collation: })
- > db.testCollection.deleteOne({$and : [{name:”sahib”},{age:4.5}]})
- { “acknowledged” : true, “deletedCount” : 1 }
- db.collection.deleteMany(, { writeConcern: , collation: })
- Delete all documents that match a specified filter.
- > db.testCollection.deleteMany({age : {$gte : 50}})
- db.collection.remove()
https://docs.mongodb.com/manual/reference/method/