简体   繁体   中英

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???

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" }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM