Skip to content

Instantly share code, notes, and snippets.

@ArturKarbone
Created January 8, 2016 16:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ArturKarbone/3a51369679633a47bfb7 to your computer and use it in GitHub Desktop.
Save ArturKarbone/3a51369679633a47bfb7 to your computer and use it in GitHub Desktop.
class Program
{
public class Person
{
public ObjectId Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class MongoFirstConcept
{
public void InsertPeople()
{
var peopleCollection = GetPeopleCollection();
peopleCollection.InsertOneAsync(new Person() { FirstName = "John", LastName = "Smith" });
peopleCollection.InsertOneAsync(new Person() { FirstName = "Will", LastName = "Smith" });
}
public async void RetrievePeople1()
{
Console.WriteLine("RetrievePeople1");
var people = await GetPeopleCollection().Find(_ => true).ToListAsync();
foreach (var person in people)
{
Console.WriteLine(person.FirstName);
}
}
public async void RetrievePeople2()
{
Console.WriteLine("RetrievePeople2");
using (var cursor = await GetPeopleCollection().FindAsync(_ => true))
{
while (await cursor.MoveNextAsync())
{
var batch = cursor.Current;
foreach (var person in batch)
{
Console.WriteLine(person.FirstName);
}
}
}
}
public void Run()
{
InsertPeople();
RetrievePeople1();
RetrievePeople2();
}
private IMongoCollection<Person> GetPeopleCollection()
{
MongoClient client = new MongoClient();
var db = client.GetDatabase("test");
return db.GetCollection<Person>("people");
}
}
static void Main(string[] args)
{
new MongoFirstConcept().Run();
Console.ReadLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment