-
Notifications
You must be signed in to change notification settings - Fork 1
MongoCollection
The MongoCollection helps you work with multiple changes to a collection by tracking and queuing actions until you use the SubmitChanges
command. This only works when you use the GetCollection
command or refer to a collection as an index value on the database.
After creating an instance of a collection you can use the InsertOnSubmit
command to queue up a document to send to the server.
MongoCollection collection = database.GetCollection("users");
//add a few documents
collection.InsertOnSubmit(new { name = "Hugo" });
collection.InsertOnSubmit(new { name = "Mary" });
collection.InsertOnSubmit(new { name = "Gwyn" });
collection.InsertOnSubmit(new { name = "Cassie" });
//nothing has been inserted yet, do it now
collection.SubmitChanges();
After loading documents into memory you can make changes to them and then use the SubmitChanges method to update the documents in the database.
Note: This example loads documents into memory to simply make the exact same change to all of them. You can use the MongoDatabase to perform a Update Query. This example is simply to illustrate how updates can work.
MongoCollection collection = database.GetCollection("users");
var documents = collection.Find()
.Greater("age", 50)
.Select();
//make each of the changes
foreach(MongoDocument document in documents) {
document += { isOld = true };
}
//documents are only changed in memory
//send the update to the server
collection.SubmitChanges();
.h2 Removing Documents
Similar to how you set documents to be inserted into the database, you must use the DeleteOnSubmit
to mark an document for deletion.
Note: This example loads documents into memory to simply delete them. You can use the MongoDatabase to perform a Delete Query. This example is simply to illustrate how deletion can work.
MongoCollection collection = database.GetCollection("users");
var documents = collection.Find()
.Greater("age", 50)
.Select();
//mark each for deletion
foreach(MongoDocument document in documents) {
collection.DeleteOnSubmit(document);
}
//documents are only changed in memory
//send the update to the server
collection.SubmitChanges();