Work with BSON Documents
mainMongoKitten uses the Document type to represent BSON data.
Key Characteristics
- Versatility: A
Documentcan represent either a dictionary (key-value pairs) or an array (ordered elements). - Initialization: You can use Swift literals to create documents.
- Protocols:
Documentconforms toCollection, allowing you to iterate over keys/values or use standard collection APIs. - Access: Use subscripts to access elements. Subscripts return
Primitive?, so you must cast them (e.g.,as? String) to use them as specific types.
Note: Avoid frequent conversion between Document and Swift Dictionary as Document is highly optimized for BSON operations.
// Dictionary-style
let documentA: Document = ["_id": ObjectId(), "username": "kitty"]
// Array-style
let documentB: Document = ["kitty", 4]
// Accessing values
let username = documentA["username"] as? String
// Iterating
for (key, value) in documentA {
// ...
}