You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET MVC中如何用C# LINQ实现MongoDB单条查询并赋值给ViewBag

实现MongoDB单条数据查询并赋值给ViewBag的LINQ写法

你要实现的MongoDB Shell查询:

db.getCollection('monitoreo').find({valor:'002'}).limit(1)

可以通过以下两种LINQ方式实现,将单条结果赋值给ViewBag:

方式一:使用AsQueryable()+LINQ扩展方法

基于集合的AsQueryable()接口,结合过滤和取第一条数据的方法:

public ActionResult Index()
{
    // 过滤valor等于"002"的第一条数据,无匹配时返回null
    monitoreoModel monitoreoItem = monitoreoCollection.AsQueryable<monitoreoModel>()
        .Where(m => m.valor == "002")
        .FirstOrDefault();

    // 将结果赋值给ViewBag
    ViewBag.MonitoreoItem = monitoreoItem;

    return View();
}

方式二:使用MongoDB驱动原生Find方法

MongoDB C#驱动支持直接调用Find方法,写法更简洁:

public ActionResult Index()
{
    // 直接查询匹配条件的第一条数据
    monitoreoModel monitoreoItem = monitoreoCollection.Find(m => m.valor == "002")
        .FirstOrDefault();

    ViewBag.MonitoreoItem = monitoreoItem;

    return View();
}

关键说明:

  • FirstOrDefault():返回匹配条件的第一条数据,若集合中无匹配项则返回null,避免因无数据抛出异常;如果确定一定有匹配数据,也可以用First(),但无匹配时会抛出异常。
  • 两种写法都对应Shell中的find({valor:'002'}).limit(1),只会从MongoDB中查询并返回一条数据,而非整个集合。

视图中使用ViewBag数据示例

在视图里通过ViewBag访问数据时,建议先判断是否为null:

@if (ViewBag.MonitoreoItem != null)
{
    <div>
        <p>Valor: @ViewBag.MonitoreoItem.valor</p>
        <!-- 可显示model的其他属性,比如@ViewBag.MonitoreoItem.其他字段名 -->
    </div>
}
else
{
    <p>未找到匹配的数据</p>
}

内容的提问来源于stack exchange,提问作者Raccoon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 06:42:28