Search code examples
mongodbmongodb-.net-driver

MongoDb: using string as Id


I have the following object:

public class Client
{
    [BsonId]
    public string Name { get; set; }
    public List<string> Links { get; set; }
}

I can create/delete it without any problems. But when I want to update the Name, it doesn't work.

var query = Query.EQ("_id", id); //id - old name
var update = Update.Set("_id", name); //name - new name
Coll.Update(query, update);

ANSWER (FROM COMMENTS) the only way, as I understand, to have additional Id:

object:

public class Client
{
    [BsonId]
    public Id { get; set; }
    public string Name { get; set; }
    public List<string> Links { get; set; } 
}

Update Name:

var query = Query.EQ("_id", ObjectId.Parse(id));
var update = Update.Set("Name", name);
Coll.Update(query, update);

Solution

  • Since the _id is the primary key, modifying _id in MongoDB is not allowed.

    If you need to change the unique name property, just add a unique index on it instead of using it as the primary key field.