我有一个名为“Test”的 MongoDB 数据库。在这个数据库中,我在“人物”集合中有一个人的集合。people 集合包含以下文档的数组:
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; }
}
鉴于当您向某人添加地址时地址 ID 会增加,并且地址是按时间顺序添加的。然后,我可以使用以下查询代码预测该人的当前状态。
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,“Sally Parker”,“New York” 101,“John Smith”,“Nevada” 102,“Fred Jones”,“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 中创建一个视图,它会给我与查询相同的结果?