简体   繁体   English

如何进行查询限制 1 linq C# MongoDB (ASP.NET MVC)

[英]How to make a query limit 1 linq C# MongoDB (ASP.NET MVC)

I want to pass data from a collection to a viewbag from mongoDB.我想将数据从集合传递到 mongoDB 的视图包。 How can I do the query (limit 1) to assign the result to the viewbag variable?如何进行查询(限制 1)以将结果分配给 viewbag 变量?

For example I want to pass the following query in LINQ例如我想在 LINQ 中传递以下查询

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

I leave the example of my controller which returns the entire list and I pass to the view我留下了我的 controller 的例子,它返回整个列表,然后我传递给视图

public ActionResult Index()
{
   List<monitoreoModel> monitoreo = monitoreoCollection.AsQueryable<monitoreoModel>().ToList();
    return View(monitoreo);
}

Please help, thanks!请帮忙,谢谢!

If you want to use Linq, you can follow the following sample:如果您想使用 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()

Above code returns only the first matching item or null if none exists.上面的代码只返回第一个匹配项,如果不存在,则返回 null。

If you want to use a simple find command instead of an aggregation pipeline, you can use the following commands.如果要使用简单的 find 命令而不是聚合管道,可以使用以下命令。 Limit is only supported in the async versions of the Find command, so you have to change the action to async : Limit仅在Find命令的async版本中受支持,因此您必须将操作更改为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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM