MongoDB使用C#驱动程序加入查询

时间:2018-10-21 03:02:29

标签: c# database mongodb nosql mongodb-csharp-2.0

我有以下代码来查询(性能是该查询平均只需要几个文档就大约3.5秒),然后将多个文档合并为一个结果。是否可以将以下代码放入联接查询中?我试图使用聚合,查找和联接,但找不到将所有部分组合在一起的方法。非常感谢您的帮助和指导。我想提高查询的性能。

List<Overview> overview = null;
//Getting areas which matches the given City
var areasInCity = await Context.Areas.Find(a => a.City.Equals(detail.City)).Project(i => i.Id).ToListAsync();
if (areasInCity.HasAny())
{
    overview = new List<Overview>();
    //Finding locations which belongs to areas we found above
    var relatedLocations =
        await Context.Locations.Find(
            l => areasInCity.Contains(l.AreaId) && l.Status.Equals(Constants.InternalStatus.Active)).ToListAsync();
    if (relatedLocations.HasAny())
    {
        foreach (var location in relatedLocations)
        {
            //Find campaigns and businesses which belongs to each location 
            var campaign = await Context.Campaigns.Find(c => c.Id.Equals(location.CampaignId)).FirstOrDefaultAsync();
            var business = await Context.Businesses.Find(b => b.Id.Equals(location.BusinessId)).FirstOrDefaultAsync();
            var overviewItem = new LocationOverview
            {
                CampaignId = campaign.Id,
                CmpaignTitle = campaign.Title,
                CampaignDescription = campaign.Description,
                BusinessName = business.BusinessName,
                BusinessId = business.Id
            };
            overview.Add(overviewItem);
        }
    }
}

0 个答案:

没有答案