使用 C# 仅获取 MongoDB 中的指定字段
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7704290/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get only a specified field in MongoDB with C#
提问by Daniele Tassone
first time i'm using MongoDB.
我第一次使用 MongoDB。
I have read this example:
我读过这个例子:
SELECT a,b FROM users WHERE age=33 db.users.find({age:33}, {a:1,b:1})
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?
但我无法将其翻译成 C#。谁能帮我?
回答by Heo ??t Hades
I have translated your query below using the new C# driver (2.2)
我已使用新的 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();
回答by Andrew Orsich
You can do it using SetFields
method of MongoCursor
class, below full example:
您可以使用类的SetFields
方法来完成MongoCursor
,下面是完整示例:
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();
回答by adi ben
//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 = db.GetCollection<User>("users");
var filteredCollection = usersCollection.AsQueryable().Where(x=> x.age < 33).Where(x=> x.a != null).Contains(x=> x.b != null);
回答by IsraelKo
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();