---
# System prepended metadata

title: MongoDB

---

# MongoDB


## Prerequisite
- NoSQL => not only SQL
- Non-Relational => You still can store relational data (just in different way)
- Document DataBase
    - Stored in `bson (binary json)` but represented as `json`
- [Some Concepts about MongoDB](https://dotblogs.com.tw/sungnoone/2012/01/11/65274)
- [Cheat Sheet](https://gist.github.com/codeSTACKr/53fd03c7f75d40d07797b8e4e47d78ec)



## Mongoose

> The **`.save()`** is an instance method of the model, while the **`.create()`** is called directly from the Model as a method call, being static in nature, and takes the object as a first parameter.

```javascript=
const mongoose = require('mongoose');

const notificationSchema = mongoose.Schema({
    "datetime" : {
        type: Date,
        default: Date.now
    },
    "ownerId":{
        type:String
    },
    "customerId" : {
        type:String
    },
    "title" : {
        type:String
    },
    "message" : {
        type:String
    }
});

const Notification = mongoose.model('Notification', notificationsSchema);


function saveNotification1(data) {
    var notification = new Notification(data);
    notification.save(function (err) {
        if (err) return handleError(err);
        // saved!
    })
}

function saveNotification2(data) {
    Notification.create(data, function (err, small) {
    if (err) return handleError(err);
    // saved!
    })
}
```

- Example2
```javascript=
router.post("/", (req, res) => {
    const user = new User({
        isAdmin: req.body.isAdmin,
        chineseName: req.body.chineseName,
    });

    user.save()
        .then((data) => res.json(data))
        .catch((err) => {
            res.json(`err: ${err}`);
        });
});
```
- Example2 (try, catch)
```javascript=
    try {
        const data = await user.save();
        res.json(data);
    } catch (err) {
        res.json(`err: ${err}`);
    }
```

- `$set`
    - https://docs.mongodb.com/manual/reference/operator/update/set/

## Mongoose (CRUD)

- `model.create(docs)`
    - returns all the data

```javascript=
model.create({
    name: "Allen",
    age: 15,
    school: "NTHU",
    FAQ: [{"Ques":"Q1", "Ans":"A1"}],
    
})
```

<hr />

- `model.find(filter, projection, { limit, skip, sort}).select()`
    - limit: `Number`
    - skip: `Number`
    - sort: `object`
        - Ex: { name: 1 }
    - `.select()`: 配合 `projection`
    - returns all the data

```javascript=
model.find(
    { name: "Allen" },
    'name age',
    {
        limit,
        skip,
        sort
    }
).select().lean();
```

<hr />

- `model.findOne(filter)`
    - returns all the data

```javascript=
model.findOne(
    { _id: "621bb7afa12afd5f13d00e4d" }
).lean();
```

<hr />

- `model.updateOne(filter, update)`
    - filter: `object`
    - update: `object`
    - MongoDB will update only the first document that matches filter regardless of the value of the multi option.
    - return `object` containing:
        - `matchedCount`
            - number of documents matched
        - `modifiedCount`
            - number of documents modified
        - `acknowledge`
            - boolean indicating everything went smoothly
        - `upsertId`
            - null or an id containing a document that had to be upserted
        - `upsertedCount`
            - number indicating how many documents had to be upserted. Will either be 0 or 1


```javascript=
model.updateOne(
    { _id: "621bb7afa12afd5f13d00e4d" },
    { name: "modified", age: 45 }
).lean();
```

<hr />

- `model.deleteOne(filter)`
    - filter: `object`
    - returns an `object` containing:
        - `deletedCount`: 1

```javascript=
model.deleteOne(
    { _id: "621bb7afa12afd5f13d00e4d" }
)
```
<hr />

- `model.deleteMany()`
    - filter: `object`
    - returns an `object` containing:
        - `deletedCount: x`: where x is the number of documents deleted.

```javascript=
model.deleteMany(
    { name: "Allen", age: { $gte: 18 } }
)
```

<hr />

- [operators](https://docs.mongodb.com/manual/reference/operator/query/)
    - `$or` `$gte`

## Cooperate with Docker

- https://hub.docker.com/_/mongo