> For the complete documentation index, see [llms.txt](https://cody-burleson.gitbook.io/rock-mountain/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cody-burleson.gitbook.io/rock-mountain/developer-guide/database/mongodb-tips-and-snippets.md).

# MongoDB Tips and Snippets

A sort of "cheat-sheet" full of useful tips and snippets...

## Rename a field

```js
jsdb.collectionName.updateMany({}, {$rename: {'StudentName': "StudentFirstName"}});
```

## Add a new field

In case you want to add a new\_field to all your collection, you have to use empty selector, and set multi flag to true (last param) to update all the documents

```js
db.documents.update(
    {},
    {$set : {"location":"/blog"}},
    {upsert:false,
    multi:true}
) 
```

* **Upsert**: If set to true, creates a new document when no document matches the query criteria.
* **Multi**: If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document.

No value:

```js
db.your_collection.update({}, {$set : {"new_field":null}}, {upsert:false, multi:true})
```

Empty array:

```js
db.your_collection.update({}, {$set : {"new_field":[]}}, {upsert:false, multi:true})
```

## Find Documents Missing a Given Field

```js
{ created : { $exists : false } }
```

or

```js
db.documents.find( { created : { $exists : false } } )
```

## Remove a Field

```js
db.documents.update(
    {},
    {$unset: {"location":1}},
    {upsert:false, multi:true}
)
```

## Delete a Document

Typically, you'd want to delete only by the document's unique `_id`, but it can also be done in the same way by some other known field value:

```js
db.documents.deleteOne( { title: "Renew Your SSL Certificate"} )
```
