Home > Software engineering >  How to make a query limit 1 linq C# MongoDB (ASP.NET MVC)
How to make a query limit 1 linq C# MongoDB (ASP.NET MVC)

Time:09-15

I want to pass data from a collection to a viewbag from mongoDB. How can I do the query (limit 1) to assign the result to the viewbag variable?

For example I want to pass the following query in 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

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

Please help, thanks!

CodePudding user response:

If you want to use Linq, you can follow the following sample:

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.

If you want to use a simple find command instead of an aggregation pipeline, you can use the following commands. Limit is only supported in the async versions of the Find command, so you have to change the action to 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);
}
  • Related