27

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?

Daniele Tassone
  • 2,104
  • 2
  • 17
  • 25
  • Someone can help me? https://stackoverflow.com/questions/62602405/how-do-i-make-my-generic-method-a-way-to-choose-which-columns-to-return-from-mon – Carlos Fernando Jun 29 '20 at 12:50

4 Answers4

34

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();
rrrr-o
  • 2,447
  • 2
  • 24
  • 52
Heo Đất Hades
  • 1,573
  • 18
  • 14
  • 2
    @HeoDatHades - above solution is not working with `FindAsync`. Can you please give me suggestion to work it with `fields` and `FindAsync` both. – prog1011 Feb 19 '18 at 11:46
  • 1
    @prog1011 I haven't used `FindAsync` yet, but I found this article https://www.codementor.io/pmbanugo/working-with-mongodb-in-net-2-retrieving-mrlbeanm5 . You can read and find out more. – Heo Đất Hades Feb 23 '18 at 06:28
26

You can do it using SetFields method of MongoCursor class, below full example:

var server = MongoServer.Create(connectionString);
var db = _server.GetDatabase("dbName");
var users = db.GetCollection("users");

var cursor = users.FindAs<DocType>(Query.EQ("age", 33));
cursor.SetFields(Fields.Include("a", "b"));
var items = cursor.ToList();
Donny V.
  • 22,248
  • 13
  • 65
  • 79
Andrew Orsich
  • 52,935
  • 16
  • 139
  • 134
5

you can use anonymous class

    public class User
    {
        public int age;
        public string  a;
        public string  b;
    }

    var collection = db.GetCollection<User>("Users");
    var results = collection.Find(Builders<User>.Filter.Eq(user => user.age, 33))
            .Project(u => new { u.a, u.b }).ToList();
IsraelKo
  • 106
  • 1
  • 5
3
//create user class
//(not sure how your class looks like)

public class User
{

public int age;

public string a;

public string b;
}

//then you can use LINQ easily

var server = MongoServer.Create(connectionString);
var db = server.GetDatabase("dbName");
var usersCollection = db.GetCollection<User>("users");

var filteredCollection = usersCollection.AsQueryable().Where(x=> x.age < 33).Where(x=> x.a != null).Contains(x=> x.b != null);
adi ben
  • 491
  • 5
  • 15