-
Notifications
You must be signed in to change notification settings - Fork 2
4 Mongo Session
Dan Geabunea edited this page Jul 22, 2015
·
2 revisions
The Mongo session represents a connection to your defined database. It can be used to perform any operation on a specific collection: query, filter, insert, update, delete, etc. Session objects can be created using the session factory.
//open a mongo session
IMongoSession mongoSession = mongoSessionFactory.OpenSession();
//save a single entity
Person scott = new Person
{
Name = "Scott",
Age = 29
};
mongoSession.Save(scott);
//save many enitities in one step
Person dan = new Person
{
Name = "Dan",
Age = 28
};
Person anna = new Person
{
Name = "Anna",
Age = 26
};
var personList = new List<Person>
{
dan,
anna
};
mongoSession.SaveBatch(personList);
//retrieve objects in the person collection
var allPersons = mongoSession.Query<Person>();
var allPersonsOver28 = mongoSession.Query<Person>()
.Where(x => x.Age > 28)
.OrderBy(x => x.Age)
.ToList();
var personById = mongoSession.Get<Person>(scott.Id);
//update
scott.Age = 40;
mongoSession.Save(scott);
//delete
mongoSession.Delete(scott);
//delete all
mongoSession.DeleteAll<Person>();
//drop all collections
mongoSession.DropAllCollections();
NOTE
The Save method will either insert or update a document, based on the value of the 'Id' property.