如何使用csharpdrivers在mongodb中使用投影

时间:2018-03-11 19:33:07

标签: mongodb mongodb-.net-driver

有人告诉我如何使用mongocsharp驱动程序中的投影从mongodb中检索数据???

    go func(i int) {
        fmt.Printf("index: %v, length of slice: %v\n", i, len(grph.EntryPoints))
        structures.CountLinks(&grph, counter, queue, tracker, grph.EntryPoints[i], i)
        wg.Done()
    }(i)

我想省略_id ...如何在此代码中插入投影???

1 个答案:

答案 0 :(得分:0)

你可以这样做:

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

User类如下:

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

当我使用var test = GetUser("john33");运行上述代码时,我得到以下结果:

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