Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get only a specified field in MongoDB with C#

Tags:

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?

like image 412
Daniele Tassone Avatar asked Oct 09 '11 14:10

Daniele Tassone


1 Answers

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(); 
like image 75
Heo Đất Hades Avatar answered Oct 09 '22 17:10

Heo Đất Hades