1gn1ter
1gn1ter

Reputation: 1444

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

Upvotes: 3

Views: 3628

Answers (1)

Kai-Rune
Kai-Rune

Reputation: 462

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.

Upvotes: 2

Related Questions