0
我有一個名爲「Test」的MongoDB數據庫。在這個數據庫中,我收集了「人員」集合中的人員。人們集合包含以下文件的數組:MongoDB投影在查詢中工作,但在創建視圖時不起作用
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; }
}
鑑於該地址標識的增加,當你添加一個地址到一個人,而該地址被按時間順序添加。然後我可以使用以下查詢代碼來計算出當前狀態。
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();
當我通過,結果我得到以下輸出迭代: 100,「薩莉·帕克」,「紐約」 101,「約翰·史密斯」,「內華達」 102,「弗雷德·瓊斯」, 「Texas」
當我嘗試創建一個包含MongoDB中相同信息的視圖時,我得不到相同的結果。我知道我做錯了什麼,但我找不到一個很好的例子來做我想做的事。
var pipeline = new[] {
PipelineStageDefinitionBuilder.Project<Person, CurrentAddressView>(projection)
};
db.CreateView<Person, CurrentAddressView>("MySpecialView", "People", pipeline);
我得到的結果是這樣的。
{
"_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)
有誰知道我可以創建MongoDB的一個觀點,即會給我相同的結果作爲查詢?