How To Query Collections Using Linq Methods?

Hey!

So I have read the documentation and learned about the Linq methods that maps to aggragate methods of mondoDB but…

I just could not put things together and haven’t seen any examples of that.

For example, here, LINQ, we see how to have a IQueryable instance and there’s this:

var query = collection.AsQueryable()
.Where(p => p.Age > 21)
.Select(p => new { p.Name, p.Age });

So how do we go one step further and actually query our collection using this query variable?

after running the code above I just receive something like:

[
    { $match: { Age: { $gt: 21 } } },
    { $project: { Name: 1, Age: 1, _id: 0 } }
]

As I said I want to learn how to fetch the documents that satisfy the conditions above.

Thanks!

Hello @Atalay_Han, welcome to the MongoDB Community forum!

 var query = collection.AsQueryable()
                       .Where(p => p.Age > 21)
                       .Select(p => p.Name);

Th variable query is of type IMongoQueryable interface. You can apply any of its methods to get the output of your choice. For example, the following will get a List and print its contents (the names of the persons).

var peopleList = query.ToList<string>();
peopleList.ForEach(s => Console.WriteLine(s));

Hey Thank you so much! That made things very clear for me!

I tried to apply this but when I code

var peopleList = query.ToList<string>();

I get the error:

Cannot resolve method ‘ToList()’, candidates are: System.Collections.Generic.List ToList(this MongoDB.Driver.IAsyncCursorSource, System.Threading.CancellationToken) (in class IAsyncCursorSourceExtensions) System.Collections.Generic.List ToList(this System.Collections.Generic.IEnumerable) (in class Enumerable)

so instead I coded this:

> var peopleList = query.ToList<string>(CancellationToken.None);

however this time I got this error:

Cannot convert instance argument type ‘{MongoDB.Driver.Linq.IMongoQueryable,System.Collections.Generic.IEnumerable,System.Linq.IQueryable}’ to ‘MongoDB.Driver.IAsyncCursorSource’

So do you know how I can solve this? Frankly I would like to find out how to map the peopleList to something like

var peopleList = query.ToList<personDTO>(CancellationToken.None);

How can this be done?

Thanks!

Try this, it works fine:

var peopleList = query.ToList()
peopleList.ForEach(p => Console.WriteLine(p));
peopleList.ForEach(p => Console.WriteLine(p.toJson()));
peopleList.ForEach(p => Console.WriteLine(p.Name));

The type of p is, I believe, is anonymous. So, you can’t map it to something like PersonDTO.

But, you can do this:

List<PersonDTO> dtoList = new List<PersonDTO>();
foreach (var p in peopleList)
{
    dtoList.Add(new PersonDTO() { Name = p.Name, Age = p.Age });
}

Now, the dtoList has the PersonDTO objects.

Oh thank you so much for this! I should have thought of a way like this to do it! :confused:

I need to be more creative I think.