Search code examples
c#mongodbmongodb-.net-driver

C# Mongodb - Get only the specified fields of documents


I have a User.cs model as follows:

uid: string
name: string
email: string
password: string
friends: List<string>

I get all users from a mongodb collection using the following code:

List<User> users = null;
var query = await _userCollection.FindAsync<User>(user => true);
users = await query.ToListAsync();

The elements in the users list have the same fields as the User model.

Now I want the returned elements or documents to have every field except password. I searched online and found that we can use SetFields but I am not able to found any code or links to follow. If possible, I would like to keep the method async.

Thanks for helping!


Solution

  • if you need just to exclude the password field from the result, you need to use Projection: https://digitteck.com/mongo-csharp/projections_in_mongo_csharp/. Also the second answer here: Mongodb -- include or exclude certain elements with c# driver (the first one is about legacy driver)