简体   繁体   English

在 C# 中从 mongodb 获取单个对象

[英]Getting a single object from mongodb in C#

I've picked up a piece of code that is using the MongoDB driver like this to get a single object from a collection...this can't be right, can it?我找到了一段代码,它使用这样的 MongoDB 驱动程序从集合中获取单个对象......这不可能是对的,是吗? Is there a better way of getting this?有没有更好的方法来获得这个?

IMongoCollection<ApplicationUser> userCollection;
....
userCollection.FindAsync(x => x.Id == inputId).Result.ToListAsync().Result.Single();

Yes, there is.就在这里。

First of all don't use FindAsync , use Find instead.首先不要使用FindAsync ,而是使用Find On the IFindFluent result use the SingleAsync extension method and await the returned task inside an async method:IFindFluent结果上,使用SingleAsync扩展方法并在异步方法中等待返回的任务:

async Task MainAsync()
{
    IMongoCollection<ApplicationUser> userCollection = ...;

    var applicationUser = await userCollection.Find(_ => _.Id == inputId).SingleAsync();
}

The new driver uses async-await exclusively.新驱动程序专门使用 async-await。 Don't block on it by using Task.Result .不要使用Task.Result阻止它。

You should limit your query before executing, otherwise you will first find all results and then only read one of it.您应该在执行之前限制您的查询,否则您将首先找到所有结果,然后只读取其中一个。

You could either specify the limit using FindOptions in FindAsync , or use the fluent syntax to limit the query before executing it:您可以在FindAsync使用FindOptions指定限制,或者在执行查询之前使用流畅的语法来限制查询:

var results = await userCollection.Find(x => x.Id == inputId).Limit(1).ToListAsync();
ApplicationUser singleResult = results.FirstOrDefault();

The result from ToListAsync will be a list but since you limited the number of results to 1, that list will only have a single result which you can access using Linq. ToListAsync的结果将是一个列表,但由于您将结果数量限制为 1,该列表将只有一个您可以使用 Linq 访问的结果。

In newer versions of MongoDB Find() is deprecated, so you can either use在较新版本的 MongoDB Find() 中已弃用,因此您可以使用

collection.FindSync(o => o.Id == myId).Single()

or或者

collection.FindAsync(o => o.Id == myId).Result.Single()

You can also use SingleOrDefault() , which returns null if no match was found instead of throwing an exception.您还可以使用SingleOrDefault() ,如果未找到匹配项,则返回 null 而不是抛出异常。

I could not get the method:我无法获得方法:

coll.Find(_ => _.Id == inputId).SingleAsync();

To work as I was getting the error在我收到错误时工作

InvalidOperationException: Sequence contains more than one element c#

So I ended up using .FirstOrDefault()所以我最终使用了.FirstOrDefault()

Example:例子:

public FooClass GetFirstFooDocument(string templatename)
        {
            var coll = db.GetCollection<FooClass>("foo");
            FooClass foo = coll.Find(_ => _.TemplateName == templatename).FirstOrDefault();
            return foo; 
        }

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

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