Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Basic MongoDB CRUD Operations

Tech 1

Two common methods to start the MongoDB service:

  1. Press Windows + R, enter services.msc, locate the MongoDB service, then start it manually.
  2. Open an elevated Command Prompt, run net start mongodb to start the service.

Next, launch the MongoDB shell: Run the mongo command in a terminal to access the MongoDB command interface. If you encounter a command not found error, add the MongoDB bin directory to your system's PATH environment variable.

Create a Database

Use the use <database-name> command to switch to or create a new database. If the specified database does not exist, MongoDB will automatically create it when you first store data in it. Example:

use ecommerceDB

Note: Running show dbs will not display empty databases, so the newly created ecommerceDB will not show up until you insert data into a collection within it.

Drop a Database

To delete the currently selected database, run the db.dropDatabase() method. This operates on the databace you have switched to with the use command.

Create a Collection

Collections are equivalent to relational database tables. Use db.createCollection("<collection-name>") to create a new collection. Example:

db.createCollection("customerColl")

Drop a Collection

To delete a specific collection, call the .drop() method on the collection object:

db.customerColl.drop()

List All Collections

To view all collections in the currently selected database, run the show collections command.

Insert Documents

Documents are the equivalent of rows in relational databases. MongoDB provides several methods to insert documents:

  1. db.collection.insertOne(): Inserts a single document. If an _id primary key is already present, it will update the existing document; otherwise, it inserts a new one.
  2. db.collection.insertMany(): Inserts multiple documents at once. Supports optional write concern and ordered insertion flags.
  3. db.collection.insert(): Inserts one or more documents. If a duplicate _id is detected, it will throw a duplicate key exception and abort the insertion.

Syntax for insertOne()

db.collection.insertOne(
   <document>,
   {
      writeConcern: <document>
   }
)

Syntax for insertMany()

db.collection.insertMany(
   [ <document 1> , <document 2>, ... ],
   {
      writeConcern: <document>,
      ordered: <boolean>
   }
)
  • writeConcern: Defines the write acknowledgment level. Defaults to 1 (acknowledged write), set to 0 for no acknowledgment.
  • ordered: Specifies whether to insert documents in the given order. Defaults to true; if set to false, MongoDB will attempt to insert all documents regardless of order.

Example Insertion

db.customerColl.insertOne({
   username: "sarahlee",
   email: "sarah@example.com",
   signupDate: new Date()
})

Update Documents

Use the db.collection.update() method to modify existing documents in a colllection.

Standard Syntax

db.collection.update(
   <query-filter>,
   <update-object>,
   {
     upsert: <boolean>,
     multi: <boolean>,
     writeConcern: <document>
   }
)

Parameter Explanations

  • query-filter: The filter to match documents to udpate, equivalent to the WHERE clause in SQL.
  • update-object: The update operations to apply, including update operators like $set.
  • upsert: If set to true, inserts a new document if no matching documents are found. Defaults to false.
  • multi: If set to true, updates all matching documents; defaults to false, only updating the first matching document.

Example Update

db.customerColl.update(
   { location: "Shanghai" },
   { $set: { membershipTier: "Premium" } }
)

The $set operator updates or adds the specified fields to the matched documents.

You can also format query results for readability using the .pretty() method:

db.customerColl.find().pretty()

Without .pretty(), results will be displayed as a single horizontal line.

There is an alternative update method using save():

db.collection.save(
   <document>,
   {
     writeConcern: <document>
   }
)

The save() method replaces the existing document if the provided _id exists, otherwise inserts a new document.

To be continued, with more content coming soon.

Tags: MongoDB

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.