我想將資料從集合傳遞到 mongoDB 的視圖包。如何進行查詢(限制 1)以將結果分配給 viewbag 變數?
例如,我想在 LINQ 中傳遞以下查詢
db.getCollection('monitoreo').find({valor:'002'}).limit(1)
我留下了我的控制器的例子,它回傳整個串列并傳遞給視圖
public ActionResult Index()
{
List<monitoreoModel> monitoreo = monitoreoCollection.AsQueryable<monitoreoModel>().ToList();
return View(monitoreo);
}
請幫忙,謝謝!
uj5u.com熱心網友回復:
如果要使用 Linq,可以按照以下示例進行操作:
var result = monitoreoCollection
.AsQueryable()
.Where(x => x.Valor == "002")
.Take(1) // This is not required, but asserts that MongoDB returns only one document
.FirstOrDefault()
上面的代碼只回傳第一個匹配項,如果不存在則回傳 null。
如果要使用簡單的 find 命令而不是聚合管道,可以使用以下命令。Limit
僅在命令async
版本中受支持Find
,因此您必須將操作更改為async
:
public async Task<ActionResult> Index()
{
var result = await (await monitoreoCollection.FindAsync(
x => x.Valor == "002",
new FindOptions<EventBase, EventBase>() { Limit = 1 }))
.FirstOrDefaultAsync();
return View(result);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/508227.html
標籤:C# asp.net-mvc mongodb 林克