Skip to content

Commit d9a82f5

Browse files
authored
Force push bugs in docs (#356)
1 parent 6654e80 commit d9a82f5

17 files changed

+2215
-169
lines changed

.spi.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
11
version: 1
22
builder:
33
configs:
4-
- documentation_targets: [MongoKitten]
4+
- documentation_targets: [MongoKitten, Meow]

README.md

Lines changed: 203 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,90 @@ A fast, pure swift [MongoDB](https://mongodb.com) driver based on [Swift NIO](ht
66

77
MongoKitten is a fully asynchronous driver, which means that it doesn't block any threads. This also means that it can be used in any asynchronous environment, such as [Vapor](https://github.com/vapor/vapor) or [Hummingbird](https://github.com/hummingbird-project/hummingbird).
88

9+
## Table of Contents
10+
11+
- [Docs \& Community](#docs--community)
12+
- [Projects](#projects)
13+
- [Installation](#installation)
14+
- [Set up MongoDB server](#set-up-mongodb-server)
15+
- [Add MongoKitten to your Swift project 🚀](#add-mongokitten-to-your-swift-project-)
16+
- [Add Meow (Optional)](#add-meow-optional)
17+
- [Basic usage](#basic-usage)
18+
- [Connect vs. LazyConnect](#connect-vs-lazyconnect)
19+
- [CRUD](#crud)
20+
- [Create](#create)
21+
- [Read](#read)
22+
- [Cursors](#cursors)
23+
- [Fetching results](#fetching-results)
24+
- [Cursors are generic](#cursors-are-generic)
25+
- [Update \& Delete](#update--delete)
26+
- [Indexes](#indexes)
27+
- [Aggregation](#aggregation)
28+
- [Transactions](#transactions)
29+
- [GridFS](#gridfs)
30+
- [About BSON](#about-bson)
31+
- [Literals](#literals)
32+
- [Just Another Collection](#just-another-collection)
33+
- [Think twice before converting between `Document` and `Dictionary`](#think-twice-before-converting-between-document-and-dictionary)
34+
- [Codable](#codable)
35+
- [Advanced Features](#advanced-features)
36+
- [Change Streams](#change-streams)
37+
- [Logging and Monitoring](#logging-and-monitoring)
38+
- [Best Practices](#best-practices)
39+
- [Connection Management](#connection-management)
40+
- [Performance Optimizations](#performance-optimizations)
41+
- [Troubleshooting](#troubleshooting)
42+
- [Meow ORM](#meow-orm)
43+
- [Setting up with Vapor](#setting-up-with-vapor)
44+
- [Setting up with Hummingbird](#setting-up-with-hummingbird)
45+
- [Models](#models)
46+
- [Queries](#queries)
47+
- [References](#references)
48+
- [Backers](#backers)
49+
50+
## Quick Start
51+
52+
Get up and running in under 5 minutes:
53+
54+
```swift
55+
// Add to Package.swift
56+
.package(url: "https://github.com/orlandos-nl/MongoKitten.git", from: "7.2.0")
57+
58+
// In your code
59+
import MongoKitten
60+
61+
// Connect to database
62+
let db = try await MongoDatabase.connect(to: "mongodb://localhost/my_database")
63+
64+
// Insert a document
65+
try await db["users"].insert(["name": "Alice", "age": 30])
66+
67+
// Query documents
68+
let users = try await db["users"].find("age" >= 18).drain()
69+
70+
// Use with Codable
71+
struct User: Codable {
72+
let name: String
73+
let age: Int
74+
}
75+
76+
let typedUsers = try await db["users"]
77+
.find()
78+
.decode(User.self)
79+
.drain()
80+
```
81+
82+
### Key Requirements
83+
84+
- **Swift**: 5.5 or later (for async/await support)
85+
- **MongoDB**: 3.6 or later
86+
- **Platforms**: macOS, iOS, Linux
87+
88+
### Optional Features Requirements
89+
90+
- **Change Streams**: MongoDB 3.6+ (replica set or sharded cluster)
91+
- **Transactions**: MongoDB 4.0+ (replica set or sharded cluster)
92+
993
# Docs & Community
1094

1195
[Join our Discord](https://discord.gg/H6799jh) for any questions and friendly banter.
@@ -22,7 +106,7 @@ A couple of MongoKitten based projects have arisen, check them out!
22106
- [Vapor's Fluent + MongoDB](https://github.com/vapor/fluent-mongo-driver)
23107
- [MongoDB + Vapor Queues](https://github.com/vapor-community/queues-mongo-driver)
24108

25-
# 🕶 Installation
109+
# Installation
26110

27111
## Set up MongoDB server
28112

@@ -54,16 +138,7 @@ Meow is an ORM that resides in this same package.
54138
.product(name: "Meow", package: "MongoKitten"),
55139
```
56140

57-
# FAQ
58-
59-
<details>
60-
<summary>I can't connect to MongoDB, authentication fails!</summary>
61-
62-
1. Make sure you've specified `authSource=admin`, unless you know what your authSource is. MongoDB's default value is really confusing.
63-
2. If you've specified an `authMechanism`, try removing it. MongoKitten can detect the correct one automatically.
64-
</details>
65-
66-
# 🚲 Basic usage
141+
# Basic usage
67142

68143
First, connect to a database:
69144

@@ -148,7 +223,7 @@ Connect's advantage is that a booted server is known to have a connection. Any i
148223

149224
LazyConnect is helpful during development, because connecting to MongoDB can be a time-consuming process in certain setups. LazyConnect allows you to start working with your system almost immediately, without waiting for MongoKitten. Another advantage is that cluster outages or offly timed topology changes do not influence app boot. Therefore, MongoKitten can simply attempt to recover in the background. However, should something go wrong it can be hard to debug this.
150225

151-
## CRUD (Create, Read, Update, Delete)
226+
## CRUD
152227

153228
Before doing operations, you need access to a collection where you store your models. This is MongoDB's equivalent to a table.
154229

@@ -157,7 +232,7 @@ Before doing operations, you need access to a collection where you store your mo
157232
let users = db["users"]
158233
```
159234

160-
### Create (insert)
235+
### Create
161236

162237
```swift
163238
// Create a document to insert
@@ -168,7 +243,7 @@ let myUser: Document = ["username": "kitty", "password": "meow"]
168243
try await users.insert(myUser)
169244
```
170245

171-
### Read (find) and the query builder
246+
### Read
172247

173248
To perform the following query in MongoDB:
174249

@@ -239,7 +314,7 @@ let users: [User] = try await users.find().decode(User.self).drain()
239314

240315
### Update & Delete
241316

242-
You can do updateOne/many and deleteOne/many the same way you'd see in the MongoDB docs.
317+
You can do update and delete entities the same way you'd see in the MongoDB docs.
243318

244319
```swift
245320
try await users.updateMany(where: "username" == "kitty", setting: ["age": 3], unsetting: nil)
@@ -309,9 +384,18 @@ for try await user in pipeline {
309384

310385
## Transactions
311386

312-
```swift
313-
try await db.transaction { transaction in
314-
// Do something with the transaction
387+
388+
Execute multiple operations atomically:
389+
390+
```swift
391+
try await db.transaction { session in
392+
let users = db["users"]
393+
let accounts = db["accounts"]
394+
395+
try await users.insert(newUser)
396+
try await accounts.insert(newAccount)
397+
398+
// Changes are only committed if no errors occur
315399
}
316400
```
317401

@@ -383,7 +467,7 @@ for try await chunk in file {
383467
}
384468
```
385469

386-
# 📦 About BSON & Documents
470+
# About BSON
387471

388472
MongoDB is a document database that uses BSON under the hood to store JSON-like data. MongoKitten implements the [BSON specification](http://bsonspec.org) in its companion project, [OpenKitten/BSON](https://github.com/OpenKitten/BSON). You can find out more about our BSON implementation in the separate BSON repository, but here are the basics:
389473

@@ -428,7 +512,7 @@ let username = documentA["username"] as? String
428512

429513
Our `Document` type is implemented in an optimized, efficient way and provides many useful features to read and manipulate data, including features not present on the Swift `Dictionary` type. On top of that, `Document` also implements most APIs present on `Dictionary`, so there is very little learning curve.
430514

431-
# 💾 Codable
515+
## Codable
432516

433517
MongoKitten supports the `Encodable` and `Decodable` (`Codable`) protocols by providing the `BSONEncoder` and `BSONDecoder` types. Working with our encoders and decoders is very similar to working with the Foundation `JSONEncoder` and `JSONDecoder` classes, with the difference being that `BSONEncoder` produces instances of `Document` and `BSONDecoder` accepts instances of `Document`, instead of `Data`.
434518

@@ -468,7 +552,103 @@ A few notes:
468552
- Nested structs and classes are most often encoded as embedded documents
469553
- You can customize the representations using encoding/decoding strategies
470554

471-
# Meow
555+
# Advanced Features
556+
557+
## Change Streams
558+
559+
MongoKitten provides powerful support for MongoDB Change Streams, allowing you to monitor real-time changes to your collections:
560+
561+
```swift
562+
// Basic change stream usage
563+
let stream = try await users.watch()
564+
565+
for try await change in stream {
566+
switch change.operationType {
567+
case .insert:
568+
print("New document: \(change.fullDocument)")
569+
case .update:
570+
print("Updated fields: \(change.updateDescription?.updatedFields)")
571+
case .delete:
572+
print("Deleted document: \(change.documentKey)")
573+
default:
574+
break
575+
}
576+
}
577+
578+
// Type-safe change streams
579+
struct User: Codable {
580+
let id: ObjectId
581+
let name: String
582+
let email: String
583+
}
584+
585+
let typedStream = try await users.watch(type: User.self)
586+
for try await change in typedStream {
587+
if let user = change.fullDocument {
588+
print("User modified: \(user.name)")
589+
}
590+
}
591+
```
592+
593+
## Logging and Monitoring
594+
595+
MongoKitten provides built-in support for logging and monitoring:
596+
597+
```swift
598+
// Add logging metadata
599+
let loggedDb = db.adoptingLogMetadata([
600+
"service": "user-api",
601+
"environment": "production"
602+
])
603+
604+
// Use the logged database
605+
let users = loggedDb["users"]
606+
```
607+
608+
## Best Practices
609+
610+
### Connection Management
611+
612+
- Use `lazyConnect` for development and non-critical services
613+
- Use `connect` for production services where immediate feedback is important
614+
- Always specify `authSource` in your connection string
615+
- Use connection pooling for better performance
616+
617+
### Performance Optimizations
618+
619+
- Use appropriate indexes for your queries
620+
- Limit result sets when possible
621+
- Use projection to fetch only needed fields
622+
- Consider using change streams instead of polling
623+
- Use batch operations for bulk updates/inserts
624+
625+
# Troubleshooting
626+
627+
<details>
628+
<summary>I can't connect to MongoDB, authentication fails!</summary>
629+
630+
1. Make sure you've specified `authSource=admin`, unless you know what your authSource is. MongoDB's default value is really confusing.
631+
2. If you've specified an `authMechanism`, try removing it. MongoKitten can detect the correct one automatically.
632+
</details>
633+
634+
<details>
635+
<summary>Change streams not working</summary>
636+
637+
1. Ensure you're connected to a replica set or sharded cluster
638+
2. Check that your user has the required privileges
639+
3. Verify that you're not trying to watch system collections
640+
</details>
641+
642+
<details>
643+
<summary>Performance issues</summary>
644+
645+
1. Check your indexes using `explain()`
646+
2. Monitor connection pool usage
647+
3. Ensure you're not fetching unnecessary fields
648+
4. Use appropriate batch sizes for bulk operations
649+
</details>
650+
651+
# Meow ORM
472652

473653
Meow works as a lightweight but powerful ORM layer around MongoKitten.
474654

@@ -592,10 +772,6 @@ app.get("users", ":id") { req async throws -> User in
592772
}
593773
```
594774

595-
# ☠️ License
596-
597-
MongoKitten is licensed under the MIT license.
598-
599-
#### Backers
775+
## Backers
600776

601-
<a href="https://github.com/ultim8p"><img src="https://avatars3.githubusercontent.com/u/4804985?s=460&v=4" width="128" height="128" /></a>
777+
<a href="https://github.com/ultim8p"><img src="https://avatars3.githubusercontent.com/u/4804985?s=460&v=4" width="128" height="128" /></a>

0 commit comments

Comments
 (0)