Skip to content

Instantly share code, notes, and snippets.

@Joannis
Last active April 25, 2017 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Joannis/44cb8a6eff2eea4b94f33b94f02bc15b to your computer and use it in GitHub Desktop.
Save Joannis/44cb8a6eff2eea4b94f33b94f02bc15b to your computer and use it in GitHub Desktop.
MongoKitten and Perfect-MongoDB
import MongoKitten
import Foundation
let client = try Server("mongodb://localhost")
// Creating a user Document
func createUser() throws -> Document {
return [
"username": "Joannis",
"age": 20,
"registrationDate": Date()
]
}
func insertNewUser() throws {
let users = client["openkitten"]["users"]
try users.insert(try createUser())
}
func removeUsers() throws {
try client["openkitten"]["users"].drop()
}
for i in 0..<1_000 {
try insertNewUser()
}
for (pos, _) in try client["openkitten"]["users"].find().enumerated() {
print(pos)
}
#if os(Linux)
import Glibc
#else
import Darwin
#endif
import Foundation
import MongoDB
let client = try MongoClient(uri: "mongodb://localhost:27017")
func createUser() -> BSON {
let doc = BSON()
doc.append(key: "username", string: "Joannis")
doc.append(key: "age", int: 20)
let registrationDate = Int(Date().timeIntervalSince1970)
doc.append(key: "registrationDate", time: registrationDate)
return doc
}
enum ApplicationError : Error {
case cannotInsert
case cannotDrop
}
func insertNewUser() throws {
let users = client.getCollection(databaseName: "perfect", collectionName: "users")
guard case .success = users.insert(document: createUser()) else {
throw ApplicationError.cannotInsert
}
}
func removeUsers() throws {
guard case .success = client.getCollection(databaseName: "perfect", collectionName: "users").drop() else {
throw ApplicationError.cannotDrop
}
}
for i in 0..<1_000 {
try insertNewUser()
}
guard let cursor = client.getCollection(databaseName: "perfect", collectionName: "users").find() else {
fatalError("No cursor")
}
for (pos, _) in cursor.enumerated() {
print(pos)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment