From charlesreid1

CRUD Operations from the Mongo Shell

The mongo shell is a Javascript command-line interface to MongoDB that can be started by running the command mongo:

$ mongo
>

Below, we cover the four basic operations of transactional databases: create, remove, update, delete (CRUD).

Create (Insert)

To insert documents into a collection:

  • db.collection.insertOne()
  • db.collection.insertMany()

Example: db.users.insertOne({name:"Sue", age:26})

Read (Query)

To read documents from a collection, use the find function:

  • db.collection.find()

Example: db.users.find({age:{$gt:18}})

Update

To update documents in a collection:

  • db.collection.updateOne()
  • db.collection.updateMany()
  • db.collection.replaceOne()

Example: db.users.updateMany( {age:{$lt:18}, $set: {status: "reject"}} )

Delete

Delete documents one at a time or en masse:

  • db.collection.deleteOne()
  • db.collection.deleteMany()