我有以下型号:
public class Car
{
public string Id {get; set;}
public IList<Driver> Drivers {get; set;}
}
public Driver
{
public string Id {get; set;}
public bool IsActive {get; set;}
}
如何选择处于活动状态的驱动程序?
var carId = "...";
var activeDriver = await _carCollection.Find(a => a.Id == carId
&& a.Drivers.Any(e=>e.IsActive))
.Project(a=>a.Drivers)
.SingleOrDefaultAsync();
此代码返回IList<Driver>
,因此所有项目。但我只想检索一个活跃的Driver
。
答案 0 :(得分:5)
您基本上需要包含positional $
operator,以便从给定的查询条件中返回匹配的数组元素。您可以使用ElementAt(-1)
var activeDriver = await _carCollection.Find(a => a.Id == carId
&& a.Drivers.Any(e => e.IsActive))
.Project(a => a.Drivers.ElementAt(-1))
.SingleOrDefaultAsync();
也可以写成:
var builder = Builders<BsonDocument>.Filter;
var activeDriver = await _carCollection.Find(
builder.Eq("Id", carId) & builder.Eq("Drivers.IsActive", true))
.Project(Builders<BsonDocument>.Projection.Include("Drivers.$"))
.SingleOrDefaultAsync();
如果我运行其中任何一个,那么我得到了发送到MongoDB的序列化输出:
{
"find" : "cars",
"filter" : { "_id" : "a", "Drivers" : { "$elemMatch" : { "IsActive" : true } } },
"projection" : { "Drivers.$" : 1, "_id" : 0 },
"limit" : 2,
"$db" : "test"
}
哪个与查询完全匹配。
答案 1 :(得分:0)
上面接受的答案对我不起作用。它什么也没返回。您可以使用以下代码:
var activeDriver = await _carCollection.AsQueryable().Where(a => a.Id == carId).SelectMany(a => a.Drivers).Where(e => e.IsActive).FirstOrDefault();
您可以选中此link