28

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?

1

4 Answers 4

35

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();
Sign up to request clarification or add additional context in comments.

2 Comments

@HeoDatHades - above solution is not working with FindAsync. Can you please give me suggestion to work it with fields and FindAsync both.
@prog1011 I haven't used FindAsync yet, but I found this article codementor.io/pmbanugo/… . You can read and find out more.
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();

1 Comment

What is Photos in the cursor declaration line?
6

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();

Comments

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.