[英]How can I read just one field in MongoDB C#?
Im trying to read just one field from the MongoDB with a given ID, but its giving me all the object... How can I do it ?我试图从给定 ID 的 MongoDB 中只读取一个字段,但它给了我所有的对象......我该怎么做? What should I do?
我应该怎么办? I tried with this repository but its returning me all the object
我尝试使用此存储库,但它返回了我所有的对象
Here is my class:这是我的课:
public class Hall
{
[BsonId]
[BsonRepresentation(BsonType.ObjectId)]
public string Id { get; set; }
public string Name { get; set; }
public List<string> Surveys { get; set; }
}
And here is my repository with the connection to Mongo:这是我与 Mongo 连接的存储库:
public Task<List<Hall>> ReadSurveysHall(string hallId)
{
var filter = Builders<Hall>.Filter.(x => x.Id, hallId);
return _mongoManager.Find(filter, MongoConstants.HallCollection);
}
I just want it to give me just the list of Survey's string.我只是希望它只给我调查字符串的列表。 Thank you in advance.
先感谢您。
In order to return only the list of surveys, you can change your method like this:为了只返回调查列表,您可以像这样更改您的方法:
public async Task<List<string>> ReadSurveysHall(string hallId)
{
var filter = Builders<Hall>.Filter.(x => x.Id, hallId);
var halls = await _mongoManager.Find(filter, MongoConstants.HallCollection);
var hall = halls.FirstOrDefault();
if (hall == null)
return new List<string>();
return hall.Surveys;
}
You can further optimize this by using a projection so that MongoDB only delivers the data that you are interested in, eg:您可以通过使用投影进一步优化这一点,以便 MongoDB 仅提供您感兴趣的数据,例如:
var projection = Builders<Hall>.Projection.Exclude(x => x.Id).Include(x => x.Surveys);
var options = new FindOptions<Hall, Hall>()
{
Projection = projection,
};
How you use that projection depends on the capabilities of _mongoManager
.如何使用该投影取决于
_mongoManager
的功能。 Take a look at the Find
methods and check whether any of these accepts a projection or some kind of FindOptions
as a parameter.查看
Find
方法并检查其中任何一个是否接受投影或某种FindOptions
作为参数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.