我必须使用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
}
LocationInfo
{
"_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实现此操作。
答案 0 :(得分:0)
您可以在嵌套属性中进行查找/联接,如下所示。以下代码使用MongoDB.Entities简洁,但对于官方驱动程序的collection.AsQueryable()
接口的查询是完全相同的。
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();
}
}
}