I have a MongoDB database called "Test". In this database I have a collection of people in the "People" collection. The people collection contains an array of the following documents:
class Person{
public int Id { get; set; }
public string Name { get; set; }
public Address[] Addresses { get; set; }
}
class Address {
public int Id { get; set; }
public string Street { get; set; }
public string City { get; set; }
public string State { get; set; }
public string Zip { get; set; }
}
Given that the Address Id increases when you add an address to a person, and that the addresses are added in chronological order. I then can project out the current state that the person is living in using the following query code.
class CurrentAddressView {
public int PersonId { get; set; },
public string Name { get; set; },
public string CurrentState { get; set; }
}
var mongoConnectionString = @"mongodb://localhost";
var db = (new MongoDB.Driver.MongoClient(mongoConnectionString)).GetDatabase("Test");
var collection = db.GetCollection<Person>("People");
var filter = Builders<Person>.Filter.Empty;
var projection = Builders<Person>.Projection.Expression(m => new CurrentAddressView
{
PersonId = m.Id,
Name = m.Name,
CurrentState = m.Addresses.OrderBy(m => m.Id).Last().State
});
var options = new FindOptions<Person, CurrentAddressView> { Projection = projection };
var results = collection.FindAsync(filter, options).Result.ToList();
When I iterate through the results I get the following output: 100, "Sally Parker", "New York" 101, "John Smith", "Nevada" 102, "Fred Jones", "Texas"
When I attempt to create a view that will contain the same information in MongoDB I do not get the same results. I know that I am doing something wrong but I cannot find a good example to do what I want to do.
var pipeline = new[] {
PipelineStageDefinitionBuilder.Project<Person, CurrentAddressView>(projection)
};
db.CreateView<Person, CurrentAddressView>("MySpecialView", "People", pipeline);
The results that I get look like this.
{
"_id" : NumberInt(100),
"Name" : "Sally Parker",
"Addresses" : [
{
"_id": NumberInt(1),
"Street": "First Street",
"City": "First Town",
"State": "Pennsylvania",
"Zip": "19200"
},
{
"_id": NumberInt(1),
"Street": "Second Street",
"City": "Second Town",
"State": "New York",
"Zip": "19300"
}
... (more results)
Does anyone know how I can create a view in the MongoDB that will give me the same results as the the query?
Found my problem. The actual projection of the data into my class happens after the data from the server is found by the query. Since views are literally read only they have no backing data objects behind them. They rely on the query and the aggregation pipeline in order for this to work correctly. After I figured out HOW to accomplish this. I've created a blog post on how I did it.
MongoDB Database Views
Hopefully this will prevent something from going through the same pains that I did.