mongodb :: MongoDb :: defaultinit
# A MongoDb database.
#
# Database are automatically created on the MongoDB server upon insertion of the
# first document into a collection.
# There is no need to create a database manually.
class MongoDb
super FinalizableOnce
# `MongoClient` used to load this database.
var client: MongoClient
# The database name.
var name: String
private var native: NativeMongoDb is noinit
init do native = new NativeMongoDb(client.native, name.to_cstring)
# Lists available collection names.
#
# Returns `null` if an error occured. See `Sys::last_mongoc_error`.
#
# ~~~
# var client = new MongoClient("mongodb://mongo:27017/")
# var db_suffix = "NIT_TESTING_ID".environ
# var db_name = "test_{db_suffix}"
# var db = client.database(db_name)
# db.collection("test").insert(new JsonObject)
# assert db.collection_names.has("test")
# ~~~
fun collection_names: Array[String] do
var res = new Array[String]
var nas = native.collection_names
if nas == null then return res
var i = 0
var name = nas[i]
while not name.address_is_null do
res.add name.to_s
name.free
i += 1
name = nas[i]
end
return res
end
# Loads or creates a collection by its `name`.
#
# ~~~
# var client = new MongoClient("mongodb://mongo:27017/")
# var db_suffix = "NIT_TESTING_ID".environ
# var db_name = "test_{db_suffix}"
# var db = client.database(db_name)
# var col = db.collection("test")
# assert col.name == "test"
# ~~~
fun collection(name: String): MongoCollection do
return new MongoCollection(self, name)
end
# Checks if a collection named `name` exists.
#
# ~~~
# var client = new MongoClient("mongodb://mongo:27017/")
# var db_suffix = "NIT_TESTING_ID".environ
# var db_name = "test_{db_suffix}"
# var db = client.database(db_name)
# assert not db.has_collection("qwerty")
# ~~~
fun has_collection(name: String): Bool do
# TODO handle error
return native.has_collection(name.to_cstring)
end
# Drop `self`, returns false if an error occured.
fun drop: Bool do return native.drop
redef fun finalize_once do native.destroy
end
lib/mongodb/mongodb.nit:301,1--378,3