MongoCollection

Represents a single collection inside a MongoDB.

All methods take arbitrary types for Bson arguments. serializeToBson() is implicitly called on them before they are send to the database. The following example shows some possible ways to specify objects.

struct MongoCollection {}

Constructors

this
this(MongoClient client, string fullPath)
Undocumented in source.
this
this(MongoDatabase db, string name)
Undocumented in source.

Members

Aliases

getIndexes
deprecated alias getIndexes = listIndexes
Undocumented in source.

Functions

aggregate
Bson aggregate(ARGS pipeline)
MongoCursor!R aggregate(S[] pipeline, AggregateOptions options)

Calculates aggregate values for the data in a collection.

count
deprecated ulong count(T query)
Undocumented in source. Be warned that the author may not have intended to support it.
countDocuments
ulong countDocuments(T filter, CountOptions options)

Returns the count of documents that match the query for a collection or view.

createIndex
string createIndex(T keys, IndexOptions indexOptions, CreateIndexOptions options)
string createIndex(IndexModel keys, CreateIndexOptions options)

Convenience method for creating a single index. Calls createIndexes

createIndexes
string[] createIndexes(const(IndexModel)[] models, CreateIndexesOptions options, string file, size_t line)

Builds one or more indexes in the collection.

deleteAll
DeleteResult deleteAll(DeleteOptions options)

Deletes all documents in the collection. The returned result identifies how many documents have been deleted.

deleteImpl
DeleteResult deleteImpl(T[] queries, DeleteOptions options, int[] limits)

Implementation helper. It's possible to set custom delete limits with this method, otherwise it's identical to deleteOne and deleteMany.

deleteMany
DeleteResult deleteMany(T filter, DeleteOptions options)

Deletes all documents matching the query filter. The returned result identifies how many documents have been deleted.

deleteOne
DeleteResult deleteOne(T filter, DeleteOptions options)

Deletes at most one document matching the query filter. The returned result identifies how many documents have been deleted.

distinct
auto distinct(string fieldName, Q query, DistinctOptions options)

Returns an input range of all unique values for a certain field for records matching the given query.

drop
void drop()

Removes a collection or view from the database. The method also removes any indexes associated with the dropped collection.

dropIndex
void dropIndex(string name, DropIndexOptions options)
void dropIndex(T keys, IndexOptions indexOptions, DropIndexOptions options)
void dropIndex(IndexModel keys, DropIndexOptions options)

Drops a single index from the collection by the index name.

dropIndexes
void dropIndexes(DropIndexOptions options)

Drops all indexes in the collection.

dropIndexes
void dropIndexes(string[] names, DropIndexOptions options)

Unofficial API extension, more efficient multi-index removal on MongoDB 4.2+

ensureIndex
deprecated void ensureIndex(const(Tuple!(string, int))[] field_orders, IndexFlags flags, Duration expire_time)
Undocumented in source. Be warned that the author may not have intended to support it.
ensureIndex
deprecated void ensureIndex(int[string] field_orders, IndexFlags flags, ulong expireAfterSeconds)
Undocumented in source. Be warned that the author may not have intended to support it.
estimatedDocumentCount
ulong estimatedDocumentCount(EstimatedDocumentCountOptions options)

Returns the count of all documents in a collection or view.

find
deprecated MongoCursor!R find(T query, U returnFieldSelector, QueryFlags flags, int num_skip, int num_docs_per_chunk)
Undocumented in source. Be warned that the author may not have intended to support it.
find
MongoCursor!R find(T query, U projection, FindOptions options)

Queries the collection for existing documents, limiting what fields are returned by the database. (called projection)

find
MongoCursor!R find(Q query, FindOptions options)

Queries the collection for existing documents.

find
MongoCursor!R find()

Queries all documents of the collection.

findAndModify
Bson findAndModify(T query, U update, V returnFieldSelector)
Bson findAndModify(T query, U update)

Combines a modify and find operation to a single atomic operation.

findAndModifyExt
Bson findAndModifyExt(T query, U update, V options)

Combines a modify and find operation to a single atomic operation with generic options support.

findOne
deprecated auto findOne(T query, U returnFieldSelector, QueryFlags flags)
Undocumented in source. Be warned that the author may not have intended to support it.
findOne
auto findOne(T query, U projection, FindOptions options)

Queries the collection for existing documents.

findOne
auto findOne(T query, FindOptions options)

Queries the collection for existing documents.

insert
deprecated void insert(T document_or_documents, InsertFlags flags)

Inserts new documents into the collection.

insertMany
InsertOneResult insertMany(T[] documents, InsertManyOptions options)

Inserts the provided document(s). If a document is missing an identifier, one is generated automatically by vibe.d.

insertOne
InsertOneResult insertOne(T document, InsertOneOptions options)

Inserts the provided document(s). If a document is missing an identifier, one is generated automatically by vibe.d.

listIndexes
MongoCursor!R listIndexes()

Returns an array that holds a list of documents that identify and describe the existing indexes on the collection.

remove
deprecated void remove(T selector, DeleteFlags flags)
deprecated void remove()

Removes documents from the collection.

replaceOne
UpdateResult replaceOne(T filter, U replacement, UpdateOptions options)

Replaces at most single document within the collection based on the filter.

update
deprecated void update(T selector, U update, UpdateFlags flags)

Performs an update operation on documents matching 'selector', updating them with 'update'.

updateImpl
UpdateResult updateImpl(T[] queries, U[] documents, O[] perUpdateOptions, UpdateOptions options, bool mustBeDocument, bool mustBeModification)

Implementation helper. It's possible to set custom per-update object options with this method, otherwise it's identical to replaceOne, updateOne and updateMany.

updateMany
UpdateResult updateMany(T filter, U replacement, UpdateOptions options)

Updates all matching document within the collection based on the filter.

updateOne
UpdateResult updateOne(T filter, U replacement, UpdateOptions options)

Updates at most single document within the collection based on the filter.

Properties

database
MongoDatabase database [@property getter]
name
string name [@property getter]

Examples

import vibe.data.bson;
import vibe.data.json;
import vibe.db.mongo.mongo;

void test()
{
	MongoClient client = connectMongoDB("127.0.0.1");
	MongoCollection users = client.getCollection("myapp.users");

	// canonical version using a Bson object
	users.insertOne(Bson(["name": Bson("admin"), "password": Bson("secret")]));

	// short version using a string[string] AA that is automatically
	// serialized to Bson
	users.insertOne(["name": "admin", "password": "secret"]);

	// BSON specific types are also serialized automatically
	auto uid = BsonObjectID.fromString("507f1f77bcf86cd799439011");
	Bson usr = users.findOne(["_id": uid]);

	// JSON is another possibility
	Json jusr = parseJsonString(`{"name": "admin", "password": "secret"}`);
	users.insertOne(jusr);
}

Using the type system to define a document "schema"

import vibe.db.mongo.mongo;
import vibe.data.serialization : name;
import std.typecons : Nullable;

// Nested object within a "User" document
struct Address {
	string name;
	string street;
	int zipCode;
}

// The document structure of the "myapp.users" collection
struct User {
	@name("_id") BsonObjectID id; // represented as "_id" in the database
	string loginName;
	string password;
	Address address;
}

void test()
{
	MongoClient client = connectMongoDB("127.0.0.1");
	MongoCollection users = client.getCollection("myapp.users");

	// D values are automatically serialized to the internal BSON format
	// upon insertion - see also vibe.data.serialization
	User usr;
	usr.id = BsonObjectID.generate();
	usr.loginName = "admin";
	usr.password = "secret";
	users.insertOne(usr);

	// find supports direct de-serialization of the returned documents
	foreach (usr2; users.find!User()) {
		logInfo("User: %s", usr2.loginName);
	}

	// the same goes for findOne
	Nullable!User qusr = users.findOne!User(["_id": usr.id]);
	if (!qusr.isNull)
		logInfo("User: %s", qusr.get.loginName);
}

Meta