Skip to content

MongoDB CRUD operations in the shell

Ben Elferink edited this page Dec 30, 2020 · 1 revision

MongoDB CRUD operations in the shell:

Beginners guide to —> mongo (shell)
Read docs for more.

  1. while in mongo shell, type show dbs to show all databases
  2. use <database name> will select that database
  3. show collections will show all arrays of documents in that database

Create:

  • db.<collection name>.insertOne( {_id: 1, name: 'Ben'} ) adds single object to db.collection
  • db.collection.insertMany([ {_id: 1, name: 'Ben'}, <document 2> , <document 3> ]) adds multiple objects to db.collection

Read:

  • db.[collection name].find({}) returns all documents (objects)
  • db.[collection name].find({age: {$gt: 18}}) returns all with age greater than 18 (using jQuery)
  • db.[collection name].findOne({_id: 69}, {name: 1}) returns only one object which it's id is 69. that object will contain only the name property (and id as a default)

Update:

  • db.[collection name].update({eyes: 'Brown'}, {$set: {eyes: 'Cocoa'}}) updates single/multiple objects with new property and/or value
  • db.[collection name].updateOne({_id: 1}, {$set: {name: 'Not Ben Anymore'}}) updates single object with new property and/or value
  • db.[collection name].updateMany({age: {$gt: 18}}, {$set: {adult: true}}) updates multiple objects with new property and/or value

Delete:

  • db.[collection name].deleteOne({name: 'Sarah'}) deletes single document that contains 'Sarah' as the 'name' value
  • db.[collection name].deleteMany({bank: {$lt: 0}}) deletes multiple documents that contains less than '0' as the 'bank' value

To delete a database (why?):

  1. open mongo shell (terminal)
  2. show dbs
  3. use [database name]
  4. db.dropDatabase() deletes data from database