MongoDB

Crud Operations

General Findings

  • A collection is analogous with a table in SQL
  • A document is analogous with a row in SQL
  • A field is analogous with a column in SQL
  • CRUD operations all target a single collection
  • Many different drivers are available
  • All write operations are atomic

Create / Insert Documents

Key Points

  • Insert methods will create a collection if the specified collection does not already exist.
  • Each document requires a unique _id field (used as primary key).
  • If an _id is not provided for the document, the Node.js driver adds an auto-generated _id to the new document.

Insert Methods

  • insertOne()
  • insertMany()

Psuedo-Insert Methods

When upsert property is set to true.

  • updateOne()
  • updateMany()
  • findAndModify()
  • findOneAndUpdate()
  • findOneAndReplace()

MongoDB - Node.js

                                
db.users.insertOne(
    {
        name: "Isaac Braun",
        age: 23,
        status: "pending"
    }
);

db.user.insertMany(
    [
        {
            name: "John Doe",
            age: 37,
            groups: ['news', 'sports']
            status: "active"
        },
        {
            name: "Jane Doe",
            age: 35,
            status: "pending"
        }
    ]
);

                            

SQL

                                
insert into users (name, age, status)
values("Isaac Braun", 23, "pending");
                            

Read Documents

MongoDB - Node.js

                                
db.users.find(
    { age: { $gt: 18 } },
    { name: 1, address: 1 }
).limit(5);
                            

SQL

                                
select top 5 name, address
from users
where age > 18;
                            

Update + Delete Documents

Update Methods

  • updateOne()
  • updateMany()
  • replaceOne()

MongoDB - Node.js

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

SQL

                                
update users
set status = "reject"
where age < 18;
                            

Delete Methods

  • deleteOne()
  • deleteMany()

MongoDB - Node.js

                                
db.users.deleteMany(
    { status: { "reject" } }
)

                            

SQL

                                
delete from users
where status = "reject";