Home > Software engineering >  MongoDb C# Class with no ObjectID
MongoDb C# Class with no ObjectID

Time:10-28

I want to have a pure class that represent a mongodb entity but with no ObjectId field. like this:

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

and to be able to use my code like this:

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

but right now i just get an exception because i need id... and bdw my insert function is working without the need of id:

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

CodePudding user response:

nvm guys i solved it like this :

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

CodePudding user response:

There are a number of options:

  • Projection:

    // 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 aggregation stage:

    var result = coll.Aggregate<User>(pipeline: PipelineDefinition<User,User>.Create("{ $unset : '_id' }")).ToList();
    
  • you may look at IgnoringExtraElements, but it will require changes in your class

  • Related