使用C#只获取MongoDB中的指定字段

时间:2011-10-09 14:44:37

标签: mongodb mongodb-.net-driver

我第一次使用MongoDB。

我已经读过这个例子:

  

SELECT a,b FROM users WHERE age = 33   db.users.find({age:33},{a:1,b:1})

但我无法将其翻译成C#。任何人都可以帮助我吗?

4 个答案:

答案 0 :(得分:22)

您可以使用SetFieldsMongoCursor方法完成此操作,完整示例如下:

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

var cursor = Photos.FindAs<DocType>(Query.EQ("age", 33));
cursor.SetFields(Fields.Include("a", "b"));
var items = cursor.ToList();

答案 1 :(得分:19)

我已使用新的C#驱动程序(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();

答案 2 :(得分:0)

//create user class
//(not sure how your class looks like)

public class User
{
[DataMember(Name = "age")]
public int age;
[DataMember(Name = "a")]
public string int a;
[DataMember(Name = "b")]
public string int b;
}

//then you can use LINQ easily

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

var filteredCollection = usersCollection.AsQueryable().Where(x=> x.age < 33).Where(x=> x.a != null).Contains(x=> x.b != null);

答案 3 :(得分:0)

您可以使用匿名类

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