简体   繁体   English

MongoDB / C#投影误解

[英]MongoDB / C# projection mis-understanding

I have the following: 我有以下内容:

var P = Builders<T>.Projection.Include(_ => _.AccountId);
var R = Mongo.Find(E).Project(P).FirstOrDefault();

Here's what I don't understand: 这是我不明白的:

With that projection, I need T to include AccountId but also _id. 按照这种预测,我需要T包含AccountId但还要包含_id。 If I do not include _id, I get the following error: 如果不包含_id,则会出现以下错误:

{"Element '_id' does not match any field or property of class T."}

If I try to exclude _id, by doing the following: 如果我尝试排除_id,请执行以下操作:

var P = Builders<T>.Projection.Include(_ => _.AccountId).Exclude(_ => _._id);
var R = Mongo.Find(E).Project(P).FirstOrDefault();

I get a different error: 我收到另一个错误:

{"Element 'CreatedOn' does not match any field or property of class T."}

CreatedOn is another field from the record in the DB. CreatedOn是数据库中记录中的另一个字段。

So, I'm afraid I don't understand how the projection really works: I need to extract one field (AccountId) and nothing else (no _id), etc (and ideally map it to a string and not a class that contains just a string, but that's a secondary problem) 因此,恐怕我不了解投影的实际工作原理:我需要提取一个字段(AccountId),而无需提取其他任何内容(没有_id),等等(理想情况下,将其映射到字符串而不是仅包含字符串的类)字符串,但这是次要问题)

What am I missing? 我想念什么?

Am I to understand that Include means take a blank slate, add all fields named in Include statements (and _id for some reason), while Exclude would mean 'take everything' and exclude specific fields? 我是否理解Include意味着要保留空白,添加在Include语句中命名的所有字段(出于某种原因,还要加上_id),而Exclude则意味着“全部”并排除特定字段? In that case, these two commands would be exclusive. 在这种情况下,这两个命令将是互斥的。

Also, I can use: 另外,我可以使用:

Expression(_ => _.AccountId)

in my projection, and I get the result I want, but this doesn't clarify Include / Exclude 在我的投影中,我得到了想要的结果,但这并不能说明“包含/排除”

The error indicates that the document returned by the database contains a field, CreatedOn , which does not exist in the class of type T . 该错误表明数据库返回的文档包含一个字段CreatedOn ,该字段在类型T的类中不存在。 You would need to add that field to the class T like so (assuming CreatedOn is a DateTime ) 您需要像这样将字段添加到类T (假设CreatedOnDateTime

public DateTime CreatedOn { get; set; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM