Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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);
like image 792
1gn1ter Avatar asked Mar 21 '26 11:03

1gn1ter


1 Answers

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.

like image 114
Kai-Rune Avatar answered Mar 24 '26 01:03

Kai-Rune