How to convert string into ObjectId

user768853 picture user768853 · Dec 14, 2011 · Viewed 41.7k times · Source

I am getting data from MongoDB and binding to a WPF datagrid.

My code selects multiple rows, retrieves IDs and updates the selected records:

var server = MongoServer.Create(this.connectionString);
var db = server.GetDatabase(DATABASE);
var viewTrue = db.GetCollection(RISKALERT_TBL);
var count = viewTrue.Count();
foreach (RiskSettings row in grdRiskAlerts.SelectedItems)
{
    viewTrue.Update(Query.EQ("ID",row.ID), Update.Set("View", "False"));
    LoadandBindData();
}

But it does not update the record.

I thought maybe row.id is returning string and ID datatype is objectId.

This query is working for other datatype except the above case.

Answer

Zaid Masud picture Zaid Masud · Dec 16, 2011

To convert a string to an ObjectId, use the ObjectId.Parse(string) method.

Also try to match on "_id" rather than "ID".

So something like:

viewTrue.Update(Query.EQ("_id", ObjectId.Parse(row.ID)), Update.Set("View", "False"));