Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.