繁体   English   中英

没有 ObjectID 的 MongoDb C# 类

[英]MongoDb C# Class with no ObjectID

我想要一个代表 mongodb 实体但没有 ObjectId 字段的纯类。 像这样:

 public class User 
    {
        //public ObjectId Id { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
    }

并且能够像这样使用我的代码:

db.GetCollection<User>("users").Find(Builders<User>.Filter.Empty).ToList();

但现在我只是得到一个例外,因为我需要 id ...... bdw 我的插入功能不需要 id 就可以工作:

public void Insert(User user)
{
     db.GetCollection<User>("users").InsertOne(user);
}

nvm 伙计们,我是这样解决的:

public IList<User> GetCollection()
{
    var tempList = new List<User>();
    var a = db.GetCollection<BsonDocument>("users").Find(Builders<BsonDocument>.Filter.Empty).ToList();
            a.ForEach(x => tempList.Add(
                new User() { FirstName = x.GetValue("FirstName").ToString(), LastName = x.GetValue("LastName").ToString() }));

    return tempList;
}

有多种选择:

  • 投影:

     // in Find var result = coll.FindSync(Builders<User>.Filter.Empty, new FindOptions<User>() { Projection = "{ _id : 0 }" }).ToList(); // in Aggregate var result = coll.Aggregate().Project("{ _id : 0 }").ToList();
  • $unset 聚合阶段:

     var result = coll.Aggregate<User>(pipeline: PipelineDefinition<User,User>.Create("{ $unset : '_id' }")).ToList();
  • 您可以查看IgnoringExtraElements ,但它需要在您的课程中进行更改

暂无
暂无

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

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