Get only a specified field in MongoDB with C#

跟風遠走 提交于 2019-12-17 23:06:52

问题


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:


You can do it using SetFields method of MongoCursor class, below full example:

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



回答2:


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



回答3:


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



回答4:


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


来源:https://stackoverflow.com/questions/7704290/get-only-a-specified-field-in-mongodb-with-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!