16

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.

6 Answers 6

26

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")); 
Sign up to request clarification or add additional context in comments.

2 Comments

This only seems to work if the string is already an ObjectId. It doesn't seem to work for arbitrary strings.
@AsadSaeeduddin yes, it's like int.Parse. If the string can't be converted to an ObjectId, of course we can't expect it to work.
9

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!

Comments

4

The easiest way I found was to use: new ObjectId(yourString) ...This will give you a MongoDB ObjectId from a string and should work with any of your queries.

Comments

2

You just need to require the ObjectId function from your mongo.

ObjectId = require('mongodb').ObjectID;

Then you can use it like that:

ObjectId(row.ID)

So you can change your line of code to:

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

Comments

1

Another way is:

myString := "5f4f321d7125461260ad9d74"

objectId, err := primitive.ObjectIDFromHex(myString)

if err != nil {
    panic("Invalid id")
}

1 Comment

This is the proper of doing it now. Thank you for the update
0

if you use mgo, you can try this one

id := "603f4d6415177136d0583d4d"
_id := bson.ObjectIdHex(id)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.