Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string into ObjectId

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.

like image 299
user768853 Avatar asked Dec 14 '11 11:12

user768853


People also ask

How is ObjectId generated?

ObjectID is automatically generated by the database drivers, and will be assigned to the _id field of each document. ObjectID can be considered globally unique for all practical purposes. ObjectID encodes the timestamp of its creation time, which may be used for queries or to sort by creation time.

Is Mongoose ObjectId a string?

Casting. MongoDB ObjectIds are typically represented using a 24 hexadecimal character string, like '5d6ede6a0ba62570afcedd3a' . Mongoose casts 24 char strings to ObjectIds for you based on your schema paths.

What is ObjectId in mongoose?

ObjectId . A SchemaType is just a configuration object for Mongoose. An instance of the mongoose. ObjectId SchemaType doesn't actually create MongoDB ObjectIds, it is just a configuration for a path in a schema.


1 Answers

I came across the same issue when setting up a public property for the ObjectID.

My property converted the ObjectID to a string, and back to an ObjectID using the following code snippet.

The ObjectID wasn't coming up as an option so I had to use the complete namespace, to access the .Parse() like this MongoDB.Bson.ObjectId.Parse

    public string Id
    {
        get { return Convert.ToString(_id); }
        set { _id = MongoDB.Bson.ObjectId.Parse(value); }
    }

Hope this helps!

like image 154
Brian Var Avatar answered Sep 21 '22 11:09

Brian Var