A Mongo collection.

Collections are automatically created on the MongoDB server upon insertion of the first document. There is no need to create a database manually.

Introduced properties

fun aggregate(pipeline: JsonArray): Array[JsonObject]

mongodb :: MongoCollection :: aggregate

Applies an aggregation pipeline over the collection.
fun count(query: JsonObject): Int

mongodb :: MongoCollection :: count

Counts the document matching query.
fun database: MongoDb

mongodb :: MongoCollection :: database

Database that collection belongs to.
protected fun database=(database: MongoDb)

mongodb :: MongoCollection :: database=

Database that collection belongs to.
fun drop: Bool

mongodb :: MongoCollection :: drop

Drops self, returns false if an error occured.
fun find(query: JsonObject, skip: nullable Int, limit: nullable Int): nullable JsonObject

mongodb :: MongoCollection :: find

Finds the first document that matches query.
fun find_all(query: JsonObject, skip: nullable Int, limit: nullable Int): Array[JsonObject]

mongodb :: MongoCollection :: find_all

Finds all the documents matching the query.
fun insert(doc: JsonObject): Bool

mongodb :: MongoCollection :: insert

Inserts a new document in the collection.
fun insert_all(docs: Collection[JsonObject]): Bool

mongodb :: MongoCollection :: insert_all

Inserts multiple documents in the collection.
fun move(database: MongoDb): Bool

mongodb :: MongoCollection :: move

Moves self to another database.
fun name: String

mongodb :: MongoCollection :: name

Name of this collection.
protected fun name=(name: String)

mongodb :: MongoCollection :: name=

Name of this collection.
fun remove(selector: JsonObject): Bool

mongodb :: MongoCollection :: remove

Removes the first document that matches selector.
fun remove_all(selector: JsonObject): Bool

mongodb :: MongoCollection :: remove_all

Removes all the document that match selector.
fun rename(name: String): Bool

mongodb :: MongoCollection :: rename

Renames self.
fun save(doc: JsonObject): Bool

mongodb :: MongoCollection :: save

Saves a new document in the collection.
fun stats: nullable JsonObject

mongodb :: MongoCollection :: stats

Retrieves statistics about the collection.
fun update(selector: JsonObject, update: JsonObject): Bool

mongodb :: MongoCollection :: update

Updates a document already existing in the collection.
fun update_all(selector: JsonObject, update: JsonObject): Bool

mongodb :: MongoCollection :: update_all

Updates all documents matching the selector.

Redefined properties

redef type SELF: MongoCollection

mongodb $ MongoCollection :: SELF

Type of this instance, automatically specialized in every class
redef fun finalize_once

mongodb $ MongoCollection :: finalize_once

Real finalization method of FinalizableOnce, will be called only once
redef init init

mongodb $ MongoCollection :: init

Loads a collection.

All properties

fun !=(other: nullable Object): Bool

core :: Object :: !=

Have self and other different values?
fun ==(other: nullable Object): Bool

core :: Object :: ==

Have self and other the same value?
type CLASS: Class[SELF]

core :: Object :: CLASS

The type of the class of self.
type SELF: Object

core :: Object :: SELF

Type of this instance, automatically specialized in every class
fun aggregate(pipeline: JsonArray): Array[JsonObject]

mongodb :: MongoCollection :: aggregate

Applies an aggregation pipeline over the collection.
protected fun class_factory(name: String): CLASS

core :: Object :: class_factory

Implementation used by get_class to create the specific class.
fun class_name: String

core :: Object :: class_name

The class name of the object.
fun count(query: JsonObject): Int

mongodb :: MongoCollection :: count

Counts the document matching query.
fun database: MongoDb

mongodb :: MongoCollection :: database

Database that collection belongs to.
protected fun database=(database: MongoDb)

mongodb :: MongoCollection :: database=

Database that collection belongs to.
fun drop: Bool

mongodb :: MongoCollection :: drop

Drops self, returns false if an error occured.
fun finalize

core :: Finalizable :: finalize

Liberate any resources held by self before the memory holding self is freed
protected fun finalize_once

core :: FinalizableOnce :: finalize_once

Real finalization method of FinalizableOnce, will be called only once
fun finalized: Bool

core :: FinalizableOnce :: finalized

Has self been finalized? (either by the GC or an explicit call to finalize)
protected fun finalized=(finalized: Bool)

core :: FinalizableOnce :: finalized=

Has self been finalized? (either by the GC or an explicit call to finalize)
fun find(query: JsonObject, skip: nullable Int, limit: nullable Int): nullable JsonObject

mongodb :: MongoCollection :: find

Finds the first document that matches query.
fun find_all(query: JsonObject, skip: nullable Int, limit: nullable Int): Array[JsonObject]

mongodb :: MongoCollection :: find_all

Finds all the documents matching the query.
fun get_class: CLASS

core :: Object :: get_class

The meta-object representing the dynamic type of self.
fun hash: Int

core :: Object :: hash

The hash code of the object.
init init

core :: Object :: init

fun insert(doc: JsonObject): Bool

mongodb :: MongoCollection :: insert

Inserts a new document in the collection.
fun insert_all(docs: Collection[JsonObject]): Bool

mongodb :: MongoCollection :: insert_all

Inserts multiple documents in the collection.
fun inspect: String

core :: Object :: inspect

Developer readable representation of self.
protected fun inspect_head: String

core :: Object :: inspect_head

Return "CLASSNAME:#OBJECTID".
intern fun is_same_instance(other: nullable Object): Bool

core :: Object :: is_same_instance

Return true if self and other are the same instance (i.e. same identity).
fun is_same_serialized(other: nullable Object): Bool

core :: Object :: is_same_serialized

Is self the same as other in a serialization context?
intern fun is_same_type(other: Object): Bool

core :: Object :: is_same_type

Return true if self and other have the same dynamic type.
fun move(database: MongoDb): Bool

mongodb :: MongoCollection :: move

Moves self to another database.
fun name: String

mongodb :: MongoCollection :: name

Name of this collection.
protected fun name=(name: String)

mongodb :: MongoCollection :: name=

Name of this collection.
intern fun object_id: Int

core :: Object :: object_id

An internal hash code for the object based on its identity.
fun output

core :: Object :: output

Display self on stdout (debug only).
intern fun output_class_name

core :: Object :: output_class_name

Display class name on stdout (debug only).
fun remove(selector: JsonObject): Bool

mongodb :: MongoCollection :: remove

Removes the first document that matches selector.
fun remove_all(selector: JsonObject): Bool

mongodb :: MongoCollection :: remove_all

Removes all the document that match selector.
fun rename(name: String): Bool

mongodb :: MongoCollection :: rename

Renames self.
fun save(doc: JsonObject): Bool

mongodb :: MongoCollection :: save

Saves a new document in the collection.
fun serialization_hash: Int

core :: Object :: serialization_hash

Hash value use for serialization
fun stats: nullable JsonObject

mongodb :: MongoCollection :: stats

Retrieves statistics about the collection.
intern fun sys: Sys

core :: Object :: sys

Return the global sys object, the only instance of the Sys class.
abstract fun to_jvalue(env: JniEnv): JValue

core :: Object :: to_jvalue

fun to_s: String

core :: Object :: to_s

User readable representation of self.
fun update(selector: JsonObject, update: JsonObject): Bool

mongodb :: MongoCollection :: update

Updates a document already existing in the collection.
fun update_all(selector: JsonObject, update: JsonObject): Bool

mongodb :: MongoCollection :: update_all

Updates all documents matching the selector.
package_diagram mongodb::MongoCollection MongoCollection core::FinalizableOnce FinalizableOnce mongodb::MongoCollection->core::FinalizableOnce core::Finalizable Finalizable core::FinalizableOnce->core::Finalizable ...core::Finalizable ... ...core::Finalizable->core::Finalizable

Ancestors

class Finalizable

core :: Finalizable

An object needing finalization
interface Object

core :: Object

The root of the class hierarchy.

Parents

class FinalizableOnce

core :: FinalizableOnce

An object to be finalized only once

Class definitions

mongodb $ MongoCollection
# A Mongo collection.
#
# Collections are automatically created on the MongoDB server upon insertion of
# the first document.
# There is no need to create a database manually.
class MongoCollection
	super FinalizableOnce

	# Database that collection belongs to.
	var database: MongoDb

	# Name of this collection.
	var name: String

	private var native: NativeMongoCollection is noinit

	# Loads a collection.
	#
	# Call `MongoDb::collection` instead.
	init do
		native = new NativeMongoCollection(
			database.client.native,
			database.name.to_cstring,
			name.to_cstring)
	end

	# Set the autogenerated last id if the `doc` does not contain one already.
	private fun set_id(doc: JsonObject) do
		var last_id = database.client.last_id
		if last_id != null then
			doc["_id"] = last_id.to_json
			database.client.last_id = null
		end
	end

	# Inserts a new document in the collection.
	#
	# If no _id element is found in document, then a new one be generated locally
	# and added to the document.
	#
	# Returns `false` 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)
	# var col = db.collection("test")
	# var doc = new JsonObject
	# doc["foo"] = 10
	# doc["bar"] = "bar"
	# doc["baz"] = new JsonArray
	# assert col.insert(doc)
	# assert doc.has_key("_id")
	# ~~~
	fun insert(doc: JsonObject): Bool do
		var res = native.insert(doc.to_bson.native)
		if res then set_id(doc)
		return res
	end

	# Inserts multiple documents in the collection.
	#
	# See `insert`.
	fun insert_all(docs: Collection[JsonObject]): Bool do
		var res = true
		for doc in docs do res = insert(doc) and res
		return res
	end

	# Saves a new document in the collection.
	#
	# If the document has an `_id` field it will be updated.
	# Otherwise it will be inserted.
	#
	# Returns `false` 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)
	# var col = db.collection("test")
	#
	# var doc = new JsonObject
	# doc["foo"] = 10
	# doc["bar"] = "bar"
	# doc["baz"] = new JsonArray
	#
	# assert col.save(doc) # will be inserted
	# assert doc.has_key("_id")
	#
	# var id = doc["_id"]
	# assert col.save(doc) # will be updated
	# assert doc["_id"] == id
	# ~~~
	fun save(doc: JsonObject): Bool do
		var bson = doc.to_bson
		var nat = bson.native
		var res = native.save(nat)
		if res then set_id(doc)
		assert nat != self #FIXME used to avoid GC crashes
		assert bson != self #FIXME used to avoid GC crashes
		return res
	end

	# Removes the first document that matches `selector`.
	#
	# Returns `false` 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)
	# var col = db.collection("test")
	# var sel = new JsonObject
	# sel["foo"] = 10
	# assert col.remove(sel)
	# ~~~
	fun remove(selector: JsonObject): Bool do
		return native.remove(selector.to_bson.native)
	end

	# Removes all the document that match `selector`.
	#
	# See `remove`.
	fun remove_all(selector: JsonObject): Bool do
		return native.remove_all(selector.to_bson.native)
	end

	# Updates a document already existing in the collection.
	#
	# No upsert is done, see `save` instead.
	#
	# ~~~
	# 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")
	# var sel = new JsonObject
	# sel["foo"] = 10
	# var upd = new JsonObject
	# upd["bar"] = "BAR"
	# assert col.update(sel, upd)
	# ~~~
	fun update(selector: JsonObject, update: JsonObject): Bool do
		return native.update(
			selector.to_bson.native,
			update.to_bson.native)
	end

	# Updates all documents matching the `selector`.
	#
	# See `update`.
	fun update_all(selector: JsonObject, update: JsonObject): Bool do
		return native.update_all(
			selector.to_bson.native,
			update.to_bson.native)
	end

	# Counts the document matching `query`.
	#
	# Returns `-1` 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)
	# var col = db.collection("test")
	# var query = new JsonObject
	# query["foo"] = 10
	# assert col.count(query) > 0
	# ~~~
	fun count(query: JsonObject): Int do
		return native.count(query.to_bson.native)
	end

	# Finds the first document that matches `query`.
	#
	# Params:
	# * `skip` number of documents to skip
	# * `limit` number of documents to return
	#
	# 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)
	# var col = db.collection("test")
	# var query = new JsonObject
	# query["foo"] = 10
	# var doc = col.find(query)
	# assert doc["foo"] == 10
	# ~~~
	fun find(query: JsonObject, skip, limit: nullable Int): nullable JsonObject do
		var q = new NativeBSON.from_json_string(query.to_json.to_cstring)
		var s = skip or else 0
		var l = limit or else 0
		var c = native.find(q, s, l)
		q.destroy
		if c == null then return null
		var cursor = new MongoCursor(c)
		if not cursor.is_ok then
			return null
		end
		var item = cursor.item
		assert cursor != self
		return item
	end

	# Finds all the documents matching the `query`.
	#
	# Params:
	# * `skip` number of documents to skip
	# * `limit` number of documents to return
	#
	# ~~~
	# 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")
	# var query = new JsonObject
	# query["foo"] = 10
	# assert col.find_all(query).length > 0
	# ~~~
	fun find_all(query: JsonObject, skip, limit: nullable Int): Array[JsonObject] do
		var s = skip or else 0
		var l = limit or else 0
		var res = new Array[JsonObject]
		var c = native.find(query.to_bson.native, s, l)
		if c == null then return res
		var cursor = new MongoCursor(c)
		while cursor.is_ok do
			res.add cursor.item
			cursor.next
		end
		return res
	end

	# Applies an aggregation `pipeline` over the collection.
	#
	# ~~~
	# 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_aggregate")
	#
	# col.drop
	#
	# col.insert("""{ "cust_id": "A123", "amount": 500, "status": "A"}""".parse_json.as(JsonObject))
	# col.insert("""{ "cust_id": "A123", "amount": 250, "status": "A"}""".parse_json.as(JsonObject))
	# col.insert("""{ "cust_id": "B212", "amount": 200, "status": "A"}""".parse_json.as(JsonObject))
	# col.insert("""{ "cust_id": "A123", "amount": 300, "status": "D"}""".parse_json.as(JsonObject))
	#
	# var res = col.aggregate("""[
	#	{ "$match": { "status": "A" } },
	#	{ "$group": { "_id": "$cust_id", "total": { "$sum": "$amount" } } },
        #       { "$sort" : { "_id": 1 } }
	# ]""".parse_json.as(JsonArray))
	#
        # assert res[0].to_json == """{"_id":"A123","total":750}"""
	# assert res[1].to_json == """{"_id":"B212","total":200}"""
	# ~~~
	fun aggregate(pipeline: JsonArray): Array[JsonObject] do
		var q = new JsonObject
		q["pipeline"] = pipeline
		var res = new Array[JsonObject]
		var c = native.aggregate(q.to_bson.native)
		if c == null then return res
		var cursor = new MongoCursor(c)
		while cursor.is_ok do
			res.add cursor.item
			cursor.next
		end
		return res
	end

	# Retrieves statistics about the collection.
	#
	# 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)
	# var col = db.collection("test")
	# assert col.stats["ns"] == "{db_name}.test"
	# ~~~
	fun stats: nullable JsonObject do
		var bson = native.stats
		if bson == null then return null
		return new JsonObject.from_bson(new BSON(bson))
	end

	# Drops `self`, returns false if an error occured.
	fun drop: Bool do return native.drop

	# Moves `self` to another `database`.
	#
	# The database will also be updated internally so it is safe to continue using
	# this collection after the move.
	# Additional operations will occur on moved collection.
	fun move(database: MongoDb): Bool do
		self.database = database
		return native.rename(database.name.to_cstring, name.to_cstring)
	end

	# Renames `self`.
	#
	# The name of the collection will also be updated internally so it is safe
	# to continue using this collection after the rename.
	# Additional operations will occur on renamed collection.
	fun rename(name: String): Bool do
		self.name = name
		return native.rename(database.name.to_cstring, name.to_cstring)
	end

	redef fun finalize_once do native.destroy
end
lib/mongodb/mongodb.nit:380,1--706,3