Search code examples
mongodbmongodb-.net-driver

how to use projection in mongodb using csharpdrivers


anyone tell me how to retrive data from mongodb using projection in mongocsharp drivers???

        var coll = dbobject.GetCollection("login");
        var query = Query<login>.EQ(e => e.username,username );
        var sa = coll.FindOne(query).ToJson();

I want to omit _id... how to insert projection in this code???


Solution

  • You can do it like this:

    public static dynamic GetUser(string username)
    {
        var context = new Context();
        var builder = Builders<User>.Filter;
        var filter = builder.Eq(x => x.Username, username);
        var projection = Builders<User>.Projection
            .Include(x => x.Name)
            .Include(x => x.Password)
            .Exclude(x => x.Id); 
        var result = context.UserCollection.Find(filter).Project(projection).SingleOrDefault();
        return result;
    }
    

    The User class is as follows:

    public class User
    {
        public ObjectId Id { get; set; }
        public string Name { get; set; }
        public string Username { get; set; }
        public string Password { get; set; }
    }
    

    When I run the above code with var test = GetUser("john33"); I get the following result:

    { "Name" : "John Smith", "Password" : "o;wdiweo;t87dsklfjdk" }