Get only a specified field in MongoDB with C#

Daniele Tassone picture Daniele Tassone · Oct 9, 2011 · Viewed 29.1k times · Source

first time i'm using MongoDB.

I have read this example:

SELECT a,b FROM users WHERE age=33 db.users.find({age:33}, {a:1,b:1})

But I can't translate it into C#. Can anyone help me?

Answer

Heo Đất Hades picture Heo Đất Hades · Feb 24, 2016

I have translated your query below using the new C# driver (2.2)

var mongoClient = new MongoClient(""mongodb://127.0.0.1:27017"");
var database = mongoClient.GetDatabase("databaseName");
IMongoCollection<Users> _collection = database.GetCollection<Users>("Users");
var condition = Builders<Users>.Filter.Eq(p => p.age, 33);
var fields = Builders<Users>.Projection.Include(p => p.a).Include(p => p.b);
var results= _collection.Find(condition).Project<Users>(fields).ToList().AsQueryable();