How to convert string into ObjectId

天涯浪子 提交于 2020-12-02 07:10:06

问题


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.


回答1:


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



回答2:


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!




回答3:


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.




回答4:


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



回答5:


Another way is:

myString := "5f4f321d7125461260ad9d74"

objectId, err := primitive.ObjectIDFromHex(myString)

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


来源:https://stackoverflow.com/questions/8503673/how-to-convert-string-into-objectid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!