MongoDB

Mastering Basic CRUD Operations in MongoDB

CRUD operations are the fundamental building blocks of interacting with MongoDB. This guide will walk you through the basics of Creating, Reading, Updating, and Deleting data in MongoDB.

Creating Databases and Collections

Creating a Database:

  • In MongoDB, databases are created implicitly. Simply switch to a new database and perform operations, and MongoDB will create the database.
> use myNewDatabase

Confirm Creation:

> show dbs

Creating a Collection:

Collections are also created implicitly. Insert a document into a collection, and MongoDB will create it.

> db.createCollection("myCollection")

Confirm Creation:

> show collections

Inserting Documents:

//Insert One Document
> db.myCollection.insertOne({ name: "Alice", age: 25 })
//Insert Multiple Documents
> db.myCollection.insertMany([
    { name: "Bob", age: 30 },
    { name: "Carol", age: 22 }
  ])

Querying Documents:

//Find All Documents
> db.myCollection.find()
//Find with Conditions
> db.myCollection.find({ age: { $gt: 25 } })
  • Operators:
    • $gt: Greater than
    • $lt: Less than
    • $eq: Equal to

Updating Documents:

//Update One Document
> db.myCollection.updateOne(
    { name: "Alice" },
    { $set: { age: 26 } }
  )
//Update Multiple Documents
> db.myCollection.updateMany(
    { age: { $lt: 30 } },
    { $set: { status: "young" } }
  )

Deleting Documents:

//Delete One Document
> db.myCollection.deleteOne({ name: "Alice" })
//Delete Multiple Documents
> db.myCollection.deleteMany({ age: { $lt: 30 } })

MongoDB CRUD operations, MongoDB create database, MongoDB insert documents, MongoDB query documents, MongoDB update documents, MongoDB delete documents.

Leave a Reply

Your email address will not be published. Required fields are marked *