【发布时间】:2021-04-22 11:09:25
【问题描述】:
我只是尝试使用 Linq 使用 Core 5 查询 MongoDB。
我的集合包含许多不同的文档架构,所以我无法创建一个类来映射。
我最终只想从查询中获得有效的 Json 输出。
这是我所拥有的:
public async Task<object> GetChapters()
{
var client = new MongoClient();
var db = client.GetDatabase("test");
var collection = db.GetCollection<BsonDocument>("test"); <-- this is a problem as my collection
doesn't have a .Net class to map to
return await collection.AsQueryable()
.Where(x => x.ChapterName == "SouthEast Chapter") <-- of course this fails
.Select(x => x.Values)
.ToListAsync();
}
我怎样才能正确地做到这一点?
【问题讨论】:
-
您在第 5 行中强调的确切问题是什么?是编译器错误吗?
-
它不会抛出异常,但由于我有一个 BsonDocument,我不知道如何执行 .where、.orderBy 等。
-
我认为您可以使用您在查询过滤器中使用的字段映射到一个类,然后选择您要使用的字段。
-
问题是我没有适用于所有可能模式的类。我认为这就是它存储 json、任何 json 的 documentDB 的美妙之处
-
您可以通过
BsonDocument的索引器访问ChapterName。因此,条件将变为:.Where(x => x["ChapterName"].AsString == "SouthEast Chapter")