-
Notifications
You must be signed in to change notification settings - Fork 15
MongoDB CRUD operations in the shell
Ben Elferink edited this page Dec 30, 2020
·
1 revision
Beginners guide to —> mongo (shell)
Read docs for more.
- while in mongo shell, type
show dbs
to show all databases -
use <database name>
will select that database -
show collections
will show all arrays of documents in that database
-
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
-
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)
-
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
-
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
- open mongo shell (terminal)
show dbs
use [database name]
-
db.dropDatabase()
deletes data from database