簡體   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