Working With MongoDB - 518
Working With MongoDB - 518
Here, after switching the database to xyzdb, xyzdb is still not available in the list of databases.
In MongoDB we have various databases and these databases have various collections.
Syntax: db.createCollection(“collection_name”)
Example: db.createCollection(“employee”)
Syntax: db.collection_name.insert({"field_name":"field_value"})
Example: db.employee.insert({"empname":"emma"})
After inserting documents into the collection, the name of the database inside which the
collection exists, can be seen in the list of databases.
B) Another way to create a collection is the direct way.
This will insert the field name and its respective value in a collection with ‘department’ as name.
NOTE: The database will be available only after we add some collections to it.
Here the database is ‘xyzdb’ and inside the database we have a 2 collection: employee and
department.
Syntax: db.collection_name.find()
This gives the documents inside a particular collection. MongoDB automatically adds a unique
id field to the document.
5.5 Drop a collection from Database
Syntax: db.collection_name.drop()
This will delete the database as well as the collections inside the database.
5.2 CRUD Operations in MongoDB
Create or insert operations add new documents to a collection. If the collection does not currently
exist, insert operations will create the collection.
db.collection_name.insert({field_name: field_value})
Here creating and inserting 2 documents into the collection ‘employee’ inside the database
xyzdb.
Run the following to insert a single document into the inventory collection :
To retrieve the document that you just inserted, query the collection with:
db.department.find()
● db.collection.find()
Update operations modify existing documents in a collection. MongoDB provides the following
methods to update documents of a collection:
● db.collection.updateOne()
The following example uses the db.collection.updateOne() method on the inventory collection to
update the client name where value is “abc Tech” to “ABC Tech”.
Here the update operation uses the ‘$set’ operator to update the value of the client name.
● db.collection.updateMany()
This method is used to update the selected values at once. Here, the selected value gets changed
at all places.
If we had 2 instances for client name: “KK Tech”, both of their departments would be updated to
“Accounting”.
Here the update operation uses the ‘$set’ operator to update the value of the client department to
“Accounting”.
● db.collection.replaceOne()
Use the remove() method to delete a particular collection with a specific field value.
Here, a document is deleted from the employee collection with empid= 25.
● db.collection.deleteOne()
Here, only one specific document is deleted at a time. In the below example, the document is
deleted using its unique id value.
db.collection.deleteMany()
***********************************END***************************************