我如何使用 Mongo.Driver.Linq 和 Mongo C# 驱动程序 2.3 return 一个包含过滤子文档的文档?
How do I return a document with filtered sub-documents using Mongo.Driver.Linq with the Mongo C# driver 2.3?
鉴于以下情况,我如何return所有包含具有 TypeOfBar == "Big" 和 的 Bars 的 Foos' Bars仅限于那些具有 TypeOfBar == "Big" 的 Bars?
public class Foo
{
public string _id { get; set; }
public List<Bar> Bars { get; set; }
}
public class Bar
{
public string _id { get; set; }
public string TypeOfBar { get; set; }
}
我可以很容易地得到第一部分(所有 Foos 和特定类型的 Bars):
var client = new MongoClient("myconnectionstring");
var db = client.GetDatabase("myDb");
var collection = db.GetCollection<Foo>("Foos");
var foos = collection.AsQueryable().Where(x => x.Bars.Any(b => b.TypeOfBar == "Big"));
但是,我很难弄清楚如何让 db return Foos 和经过过滤的 Bars 列表。
如果您只想过滤掉类型为 "Big" 的 Foos,您应该应用 ElemMatch
投影:
var res = collection.Find(x => x.Bars.Any(b => b.TypeOfBar == "Big"))
.Project(Builders<Foo>.Projection.ElemMatch(x=>x.Bars, b=>b.TypeOfBar == "Big"));
你会遇到的问题:投影会 return BSon。也许这就是你需要的,你可以接受它,如果不是,你应该将 Bson 反序列化为你的 Foo class。完整的查询我看起来像:
var res = collection.Find(x => x.Bars.Any(b => b.TypeOfBar == "Big"))
.Project(Builders<Foo>.Projection.ElemMatch(x=>x.Bars, b=>b.TypeOfBar == "Big"))
.ToEnumerable()
.Select(b=>BsonSerializer.Deserialize<Foo>(b))
.ToList();
鉴于以下情况,我如何return所有包含具有 TypeOfBar == "Big" 和 的 Bars 的 Foos' Bars仅限于那些具有 TypeOfBar == "Big" 的 Bars?
public class Foo
{
public string _id { get; set; }
public List<Bar> Bars { get; set; }
}
public class Bar
{
public string _id { get; set; }
public string TypeOfBar { get; set; }
}
我可以很容易地得到第一部分(所有 Foos 和特定类型的 Bars):
var client = new MongoClient("myconnectionstring");
var db = client.GetDatabase("myDb");
var collection = db.GetCollection<Foo>("Foos");
var foos = collection.AsQueryable().Where(x => x.Bars.Any(b => b.TypeOfBar == "Big"));
但是,我很难弄清楚如何让 db return Foos 和经过过滤的 Bars 列表。
如果您只想过滤掉类型为 "Big" 的 Foos,您应该应用 ElemMatch
投影:
var res = collection.Find(x => x.Bars.Any(b => b.TypeOfBar == "Big"))
.Project(Builders<Foo>.Projection.ElemMatch(x=>x.Bars, b=>b.TypeOfBar == "Big"));
你会遇到的问题:投影会 return BSon。也许这就是你需要的,你可以接受它,如果不是,你应该将 Bson 反序列化为你的 Foo class。完整的查询我看起来像:
var res = collection.Find(x => x.Bars.Any(b => b.TypeOfBar == "Big"))
.Project(Builders<Foo>.Projection.ElemMatch(x=>x.Bars, b=>b.TypeOfBar == "Big"))
.ToEnumerable()
.Select(b=>BsonSerializer.Deserialize<Foo>(b))
.ToList();