07.02.2024

How to create, update, and delete MongoDB documents

The realm of MongoDB extends far beyond the initial installation process, encompassing a suite of imperative operations essential for proficient database management. In this comprehensive guide, we will intricately explore three pivotal facets of MongoDB utilization: the creation, updating, and deletion of documents. MongoDB's unique document-oriented NoSQL architecture affords unparalleled flexibility and scalability, emphasizing the significance of mastering these fundamental operations for seamless and efficient data manipulation.

MongoDB create documents

At the first we need to connect to the MongoDB server, we will use mongoshell for that task at the localhost server:

mongosh

Screenshot №1 — MongoSH

Alright we are in! Switch to the database or create new by the command:

use hh

Screenshot №2 — Create DB

Now we switched our ahead input command to hh Database. But no one DB can't exist without collection, that group of future MongoDB docs, let's create them, by command below:

db.createCollection ('FS')

Screenshot №3 — Create Collection

After preparation step, create needed document, by the command:

db.FS.insertOne ({
id: "value1",
name: "value2",
surname:"value3"})

Screenshot №4 — Create one document

If we want create many MongoDB documents at one transaction than we need to use another method for collection:

db.FS.insertMany ([
{id: "22", name: "Jhon"},
{hobby:"dance"}])

Screenshot №5 — Create many MongoDB documents

As yo can notice we use {} sign for indicate canvas of document and  sing [] for indicate range of collection. Then we need to make sure that files was created, by method of collection:

db.FS.find()

Screenshot №6 — Check created files

In the picture we can see list of the created documents before.

MongoDb update documents

For Update we will use follow algorithm, at firts indicate filter value and second replace target:

db.FS.updateOne (
{ id: "valuel" },
{ $set: { id: "newvalue"} }
);

Screenshot №7 — Update value

At the end of operation we see summary info about moderation: matched count, modified count and etc.

MongoDb delete documents

For deletion we will use follow command:

db.FS.deleteOne({id: "newvalue"})

Screenshot №8 — Delete document

For make sure that command finished successfully, then type find command:

db.FS.find()

In the picture above we don't see deleted document, that means deletion was done.

In conclusion, this guide serves as a compass through the multifaceted landscape of MongoDB operations, empowering users to navigate the nuances of document creation, updating, and deletion with confidence and precision. As users continue to harness the power of MongoDB, these foundational skills will undoubtedly prove invaluable in managing data with dexterity and efficiency.