【问题标题】:MongoDb C# Class with no ObjectID没有 ObjectID 的 MongoDb C# 类
【发布时间】:2021-12-12 22:07:39
【问题描述】:

我想要一个代表 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);
}

【问题讨论】:

    标签: c# mongodb mongodb-query


    【解决方案1】:

    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;
    }
    

    【讨论】:

    • 这是一种不好的方法,因为它将是客户端转换而不是涉及服务器
    【解决方案2】:

    有多种选择:

    • 投影:

      // 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,但这需要您的班级进行更改

    【讨论】:

    • 看起来比我的解决方案更好,谢谢。
    • 将问题标记为已解决,然后减少对其的关注
    • 我该怎么做?
    • 点击接受答案:stackoverflow.com/tour
    猜你喜欢
    • 1970-01-01
    • 2016-05-30
    • 1970-01-01
    • 1970-01-01
    • 2019-03-24
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多