basic mongodb docs

This commit is contained in:
Joannis Orlandos 2018-01-02 14:08:16 +01:00
parent 0110024b84
commit 9a8b7ed417
6 changed files with 221 additions and 4 deletions

View File

View File

View File

@ -0,0 +1,109 @@
# Using MongoDB
The [vapor/mongodb](https://github.com/OpenKitten/MongoKitten) package is an extremely performant, reactive and pure swift MonogDB driver. It provides a simple interface to MongoDB for powerful features.
On top of [vapor/mysql](https://github.com/vapor/mysql), we have built [vapor/fluent-sqlite](https://github.com/vapor/fluent-sqlite) which allows SQLite databases to be used with Fluent.
## Just MongoDB
This package works really well with _and_ without Fluent. To include this package in your project, simply add it to your Package manifest.
```swift
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "Project",
dependencies: [
...
.package(url: "https://github.com/OpenKitten/MongoKitten.git", .revision("master/5.0")),
],
targets: [
.target(name: "Project", dependencies: ["MongoKitten", ... ])
]
)
```
If this is your first time adding a dependency, you should read our introduction to [Package.swift](../../getting-started/spm.md).
If this is your first time using MongoDB, have a look at the [setup guides](https://docs.mongodb.com/manual/administration/install-community/).
The official documentation assumed either the MongoDB shell or one of their more popular (official) drivers.
Please refer to [the MongoKitten interpretation guide](interpreting.md) before reading the [official documentation](https://docs.mongodb.com/manual/tutorial/getting-started/).
Use `import MongoKitten` to access the APIs.
## With Fluent
MySQL works well Fluent, you just need to make sure to add the [vapor/fluent-mysql](https://github.com/vapor/fluent-mysql) package to your project.
To do this, add the Fluent MySQL package to your Package manifest.
```swift
// swift-tools-version:4.0
import PackageDescription
let package = Package(
name: "Project",
dependencies: [
...
.package(url: "https://github.com/vapor/fluent-mysql.git", .revision("beta")),
],
targets: [
.target(name: "Project", dependencies: ["FluentMySQL", ... ])
]
)
```
If this is your first time adding a dependency, you should read our introduction to [Package.swift](../../getting-started/spm.md).
Use `import FluentMySQL` to access MySQL's Fluent compatible APIs. [Learn more about the Fluent APIs here](../../fluent/getting-started/provider.md)
### Setting up services
In order to set up MySQL with Fluent you first need to register the Fluent provider:
```swift
try services.provider(FluentProvider())
```
After this, you need to register the MySQL config and database.
```swift
services.instance(FluentMySQLConfig())
var databaseConfig = DatabaseConfig()
let username = "<mysql-user-here>"
let password = "<mysql-pass-here>"
let database = "<mysql-database>"
let db = MySQLDatabase(hostname: "localhost", user: username, password: password, database: database)
databaseConfig.add(database: db, as: .mysql)
services.instance(databaseConfig)
```
Notice the variable `mysqlDB`. This is an identifier for the MySQL database.
You need to create an identifier for each database you attach to Fluent.
The following identifer can be global, or as a static variable in an extension on `DatabaseIdentifier`.
```swift
extension DatabaseIdentifier {
static var mysql: DatabaseIdentifier<MySQLDatabase> {
return .init("foo")
}
}
```
Last, you can specify migrations for Fluent to execute. This can be used for creating and altering schemas and migrating data within the table.
Fluent `Model`s that conform to the protocol `Migration` automatically inherit a migration for schema creation. Nothing needs to be programmed for this.
```swift
var migrationConfig = MigrationConfig()
migrationConfig.add(model: MyModel.self, database: .mysql)
services.instance(migrationConfig)
```
More info on working with Fluent can be found [here](../../fluent/getting-started/getting-started.md).

View File

@ -0,0 +1,107 @@
# Interpreting official MongoDB tutorials
https://docs.mongodb.com/manual/reference/ has a lot of tutorials on every detail of MongoDB.
Using them in MongoKitten can be a bit tricky. This guide will explain how they are best applied.
## Documents/BSON Data
MongoDB writes Documents in a JSON-like syntax. The following Documents are taken from the documentation on the MongoDB website.
```js
var document0 = {
"_id" : ObjectId("512bc95fe835e68f199c8686"),
"author" : "dave",
"score" : 80,
"views" : NumberLong(100),
"awesome": true,
"users": [
{ _id: 2, user: "ijk123", status: "A" },
{ _id: 3, user: "xyz123", status: "P" },
{ _id: 4, user: "mop123", status: "P" }
]
}
```
These Documents read to this equivalent in BSON.
```swift
let document0: Doucment = [
"_id": try ObjectId("512bc95fe835e68f199c8686")
"author": "dave",
"score": Int32(80),
"views": 100,
"aweosme": true,
"users": [
["_id": 2, "user": "ijk123", "status": "A"],
["_id": 3, "user": "xyz123", "status": "P"],
["_id": 4, "user": "mop123", "status": "P"]
]
]
```
As you see, ObjectId works similarly but initializing an creating ObjectId from a String can throw an error.
More information about BSON, the MongoDB data type [on this page](bson.md).
Integers in MongoDB are Int32 by default, MongoKitten uses Int64 by default.
MongoDB and MongoKitten can often use the 2 interchangeably with the exception of large numbers that do not fit in an Int32 (and are requested as Int32).
In Swift your dictionary literals dont start with `{` and dont end with `}` but instead also use `[` and `]` for dictionaries.
Dictionaries in Swift require a `String` to have quotes (`"`) around them. In JavaScript syntax this is optional.
## Selecting databases/collections
In the shell `use mydatabase` selects the database named "mydatabase". From here you can use `db.mycollection.find()` to fetch all data in the collection.
In MongoKitten, you can subscript the server and database.
Subscripting the server selects a database, and subscripting the database selects a collection.
Usually you'll be working with a single database, so the following code connects to a single database named "example-db".
```swift
// Connect to the localhost database `example-db` without credentials
let database = try Database.connect(server: "mongodb://localhost:27017", database: "mongokitten-example-db", worker: eventLoop).await(on: eventLoop)
// Select a collection
let mycollection = mydatabase["mycollection"]
// Query all entities
try mycollection.find()
```
## Common operations in collections
Most operations are available on a collection object.
By typing `mycollection.` , Swift will autocomplete a list of available methods.
For inserting you can use `insert` which have various parameters which you can use.
Most parameters have a default and can thus be left out of not needed.
```swift
```
## Aggregates
If you followed this article you should know the basics of MongoKitten aggregates. If you, at any point, need a specific stage, you can look for the stage by the MongoDB name in the documentation or make use of autocomplete.
All aggregates can be quickly accessed using by simply typing a dot (.) inside the pipeline array literal like you would for enum cases. This will autocomplete to all available static functions that can help you create a stage. If you miss a stage or want to create a stage manually you can do so by providing a BSONDocument like this:
let stage = Stage([
"$match": [
"username": [
"$eq": "Joannis"
]
]
])
The stage must be equal to the Document representation of the stage operators described here.
You can then add this stage as one of the values in the array.
Queries
MongoDB queries can work if converted to a Document. If you do this, you must either use a literal query like below or write it using the query builder described here.
let query = Query(document)
let literalQuery: Query = [
"age": [
"$gte": 15
]
]
Sorting and Projecting
Sorts and projections have quite a bit of sugarcoating around them for readability and MongoDB-newcomers as explained here.
Both objects can be wrapped around a Document like you can with Query :
let sort = Sort(document)
let projection = Projection(document)

View File

@ -16,7 +16,7 @@ It responds with `"Hello world!"` using futures.
```swift
router.on(.get, to: "hello", "world") { request in
return try Response(body: "Hello world!")
return try Response(body: "Hello world!")
}
```

View File

@ -57,9 +57,10 @@ pages:
- 'Transaction': 'fluent/transaction.md'
- 'Database': 'fluent/database.md'
- 'Databases':
# - 'SQLite':
# - 'Package': 'databases/sqlite/getting-started.md'
# - 'Overview': 'databases/sqlite/overview.md'
- 'MongoDB':
- 'Getting Started': 'databases/mongodb/getting-started.md'
- 'Basics': 'databases/mongodb/basics.md'
- 'Interpreting tutorials': 'databases/mongodb/interpreting.md'
- 'MySQL':
- 'Getting Started': 'databases/mysql/getting-started.md'
- 'Basics': 'databases/mysql/basics.md'