knowledge/technology/applications/development/MongoDB.md

125 lines
5.9 KiB
Markdown
Raw Normal View History

2023-12-04 10:02:23 +00:00
---
website: https://www.mongodb.com
obj: application
---
2024-01-16 08:35:22 +00:00
# MongoDB
2024-02-12 14:32:44 +00:00
MongoDB is a popular NoSQL database that is document-oriented and designed for scalability and flexibility. You can work with MongoDB in a GUI with [MongoDB Compass](MongoDB%20Compass.md).
2023-12-04 10:02:23 +00:00
## Docker-Compose
```yml
version: '3'
services:
mongo:
image: mongo
restart: always
environment:
MONGO_INITDB_ROOT_USERNAME: root
MONGO_INITDB_ROOT_PASSWORD: password
volumes:
2024-01-16 08:35:22 +00:00
- ./db:/data/db
2023-12-04 10:02:23 +00:00
ports:
- "27017:27017"
```
## Usage
### **Connecting to MongoDB**
To connect to MongoDB using the `mongo` shell:
`mongo mongodb://<username>:<password>@<hostname>:<port>/<database>`
Replace `<username>`, `<password>`, `<hostname>`, `<port>`, and `<database>` with your own values.
### **Working with Databases**
To create a new database: `use <database>`
To show a list of all databases: `show dbs`
To switch to a different database: `use <database>`
To drop a database: `use <database>; db.dropDatabase()`
### **Working with Collections**
To create a new collection: `db.createCollection("<collection>")`
To show a list of all collections in the current database: `show collections`
To drop a collection: `db.<collection>.drop()`
### **Inserting Data**
To insert a single document: `db.<collection>.insertOne(<document>)`
To insert multiple documents: `db.<collection>.insertMany([<document1>, <document2>, ...])`
### **Querying Data**
To find all documents in a collection: `db.<collection>.find()`
To find documents that match a specific condition: `db.<collection>.find(<query>)`
To limit the number of documents returned: `db.<collection>.find().limit(<limit>)`
To sort documents by a field: `db.<collection>.find().sort({<field>: <1 or -1>})`
To count the number of documents: `db.<collection>.count()`
### **Updating Data**
To update a single document: `db.<collection>.updateOne(<filter>, <update>)`
To update multiple documents: `db.<collection>.updateMany(<filter>, <update>)`
To replace a document: `db.<collection>.replaceOne(<filter>, <replacement>)`
### **Deleting Data**
To delete a single document: `db.<collection>.deleteOne(<filter>)`
To delete multiple documents: `db.<collection>.deleteMany(<filter>)`
To delete all documents in a collection: `db.<collection>.deleteMany({})`
### Filters
2024-01-16 08:35:22 +00:00
Usage:
```json
{ "field": { "$mod": "value" } }
```
- `$eq`: The `$eq` operator matches documents where the value of a field equals a specified value.
- `$ne`: The `$ne` operator matches documents where the value of a field is not equal to a specified value.
- `$gt`: The `$gt` operator matches documents where the value of a field is greater than a specified value.
- `$gte`: The `$gte` operator matches documents where the value of a field is greater than or equal to a specified value.
- `$lt`: The `$lt` operator matches documents where the value of a field is less than a specified value.
- `$lte`: The `$lte` operator matches documents where the value of a field is less than or equal to a specified value.
- `$in`: The `$in` operator matches documents where the value of a field equals any value in a specified array.
- `$nin`: The `$nin` operator matches documents where the value of a field does not equal any value in a specified array.
- `$and`: The `$and` operator performs a logical AND operation on an array of two or more expressions and selects the documents that satisfy all the expressions.
- `$or`: The `$or` operator performs a logical OR operation on an array of two or more expressions and selects the documents that satisfy at least one of the expressions.
- `$not`: The `$not` operator performs a logical NOT operation on the specified expression and selects the documents that do not match the expression.
2024-02-12 14:32:44 +00:00
- `$type`: The `$type` operator matches documents where a specified field has a specific [BSON](../../files/BSON.md) type.
- `$regex`: The `$regex` operator matches documents where a specified field matches a [regular expression](../../tools/Regex.md).
2024-01-16 08:35:22 +00:00
- `$text`: The `$text` operator performs a text search on the specified field(s).
- `$elemMatch`: The `$elemMatch` operator matches documents where a specified array field contains at least one element that matches all the specified conditions.
- `$size`: The `$size` operator matches documents where a specified array field has a specific size.
2024-01-17 07:31:39 +00:00
- `$exists`: The `$exists` operator matches documents that contain or do not contain a specified field, including documents where the field value is `null`.
2023-12-04 10:02:23 +00:00
**Example:**
```js
db.users.find(
{
$and: [
{ status: "active" },
{ age: { $gt: 28 } }
]
}
)
```
### Update Modifiers
2024-01-16 08:35:22 +00:00
- `$set`: The `$set` operator updates the value of a field in a document.
- `$unset`: The `$unset` operator removes a field from a document.
- `$inc`: The `$inc` operator increments the value of a field in a document.
- `$mul`: The `$mul` operator multiplies the value of a field in a document.
- `$min`: The `$min` operator updates the value of a field in a document if the new value is lower than the existing value.
- `$max`: The `$max` operator updates the value of a field in a document if the new value is higher than the existing value.
- `$rename`: The `$rename` operator renames a field in a document.
- `$addToSet`: The `$addToSet` operator adds a value to an array field in a document if the value does not already exist in the array.
- `$push`: The `$push` operator appends a value to an array field in a document.
- `$pull`: The `$pull` operator removes a value from an array field in a document.
- `$currentDate`: The `$currentDate` operator sets the value of a field in a document to the current date and time.
- `$each`: The `$each`¥ operator can be used with `$addToSet` and `$push` to append multiple values to an array field in a document.
- `$sort`: The `$sort` operator can be used with `$push` to sort the elements in an array field in a document.
2023-12-04 10:02:23 +00:00
**Example:**
```js
db.users.updateOne(
{ name: "John Doe" },
{
$set: { age: 35 },
$addToSet: { interests: "Hiking" },
$unset: { status: "" }
}
)
```