c# - mongo 加入嵌套集合
问题描述
我必须使用 linq 加入集合 Location 和 LocationInfo 并获得以下异常
System.NotSupportedException: '$project 或 $group 不支持 {document}。'
并尝试了以下 C# 代码
IMongoClient client = new MongoClient();
MongoUrl url = new MongoUrl("mongodb://localhost:27017/Database");
MongoClientSettings settings = MongoClientSettings.FromUrl(url);
client = new MongoClient(settings);
IMongoDatabase database = client.GetDatabase(url.DatabaseName);
var location = database.GetCollection<Location>("Location").AsQueryable();
var locationInfo = database.GetCollection<LocationInfo>("LocationInfo").AsQueryable();
var res = (from loc in locationInfo
from li in loc.ServiceLocation
join locs in location
on li.LocationId equals locs._id
select new LocationInfo
{
LocationName = loc.LocationName,
ServiceLocation = loc.ServiceLocation
});;
var ret = res.ToList();
地点
{
"_id" : "c1828bf1-1ea0-4c48-932f-9d8ba4a19003",
"LocationNumber" : 12345
}
位置信息
{
"_id" : "35cfd485-b1eb-4724-a07d-9b0885b6fb6c",
"LocationName" : "AA Country",
"IsActive" : true,
"ServiceLocation" : [
{
"LocationId" : "c1828bf1-1ea0-4c48-932f-9d8ba4a19003",
"Addresses" : [
{
"AddressId" : "9235bb19-cdbf-46a8-af96-cd519d081380",
"Line1" : "xx",
"Line2" : null,
"City" : "xx",
"State" : "OH",
"IsActive" : true
}
]
}
]}
告诉我如何使用 c# Linq 来实现这个操作。
解决方案
您可以在嵌套属性中进行查找/连接,如下所示。collection.AsQueryable()
以下代码使用 MongoDB.Entities 为简洁起见,但查询与官方驱动程序的接口完全相同。
using MongoDB.Entities;
using MongoDB.Driver.Linq;
using System.Linq;
namespace StackOverflow
{
public class Location : Entity
{
public string LocationNumber { get; set; }
}
public class LocationInfo : Entity
{
public string LocationName { get; set; }
public ServiceLocation[] ServiceLocation { get; set; }
}
public class ServiceLocation
{
public string LocationId { get; set; }
public Address[] Addresses { get; set; }
}
public class Address
{
public string AddressId { get; set; }
}
public class Program
{
private static void Main(string[] args)
{
new DB("Location");
var res =
DB.Queryable<LocationInfo>()
.SelectMany(li => li.ServiceLocation, //unwind the service locations
(li, sl) => new { locName = li.LocationName, serLoc = sl }) //project needed data in to anonymous type
.Join(DB.Queryable<Location>(), //foregin collection
x => x.serLoc.LocationId, //local field in anonymous type from unwind above
l => l.ID, //foreign field
(x, l) => new { LocationName = x.locName, ServiceLocation = x.serLoc }) //project in to final anonymous type
.ToList();
}
}
}
推荐阅读
- javascript - 用新值替换 localStorage
- javascript - 为什么我使用 Deferred 的 jQuery 对话框不等待用户选择?
- search - 过滤表上的表搜索?
- android - DialogFlow 在 WebView Android 中不起作用
- angular - 与使用桌面的移动设备相比,Angular 应用程序加载速度较高
- oracle - 如何对每个进行分组并按最大值排序
- javascript - Redux 传奇没有调用 API
- html - 离子新手如何使列表项更大
- freertos - FreeRTos 高频 ISR
- java - 尝试导出数据时发生 Oracle SQL Developer InvocationTargetException