MongoDB – Delete Document

MongoDB Delete Document Use db.colloction.remove() method to delete any document from MongoDB collection on basis of critaria. Syntax: > db.colloction.remove(CONDITION) Delete Matching Document Now use the following command deletes a specific document from MongoDB collection with user_name = rahul. > db.users.remove({“user_name”:”rahul”}) The above command will remove all document having user_name rahul. To remove only first matching document from collection use following command. > db.users.remove({“user_name”:”rahul”},1) Delete All Documents in Collection Use the following command with no deletion criteria to delete all documents from the specific collection. For example, below will delete…

Read More

MongoDB – Update Document

MongoDB Update Document Use db.collection.update() method to update document in MongoDB database. Syntax: > db.users.update(CONDITION, UPDATED DATA, OPTIONS) Find Current Document First find the current document in collection with user_name = rahul. We have already inserted documents in previous tutorial like below. > db.users.find().pretty({“user_name”:”rahul”}) { “_id” : ObjectId(“59a7aef2de55e8e213bf3f26”), “id” : 1001, “user_name” : “rahul”, “name” : [ { “first_name” : “Rahul” }, { “middle_name” : “” }, { “last_name” : “Kumar” } ], “email” : “[email protected]”, “designation” : “Founder and CEO”, “location” : “India” } Update Document Now change location…

Read More

MongoDB – Query Document

MongoDB Query Document Use db.collection.find() method to query collection for available documents. Syntax > db.COLLECTION_NAME.find(condition) Search All Documents Execute find() function on the collection without any condition to get all the availabel documents in collection. > db.users.find() You can also use pretty() function with above command to show formatted output. > db.users.find().pretty(); Output { “_id” : ObjectId(“59a01b102427abe3470644db”), “id” : 1001, “user_name” : “rahul”, “name” : [ { “first_name” : “Rahul” }, { “middle_name” : “” }, { “last_name” : “Kumar” } ], “email” : “[email protected]”, “designation” : “Founder and CEO”,…

Read More

MongoDB – Insert Document

MongoDB Insert Document Use db.collection.insert() method to insert new document to MongoDB collection. You don’t need to create the collection first. Insert method will automatically create collection if not exists. Syntax > db.COLLECTION_NAME.insert(document) Insert Single Document Insert single ducument using the insert() method. It’s required a json format of document to pass as arguments. > db.users.insert({ “id”: 1001, “user_name”: “rahul”, “name”: [ {“first_name”: “Rahul”}, {“middle_name”: “”}, {“last_name”: “Kumar”} ], “email”: “[email protected]”, “designation”: “Founder and CEO”, “location”: “India” }) Output: WriteResult({ “nInserted” : 1 }) Insert Multiple Documents To insert multiple…

Read More