如何将字符串转换为ObjectId
我正在从 MongoDB 获取数据并绑定到 WPF 数据网格。
我的代码选择多行,检索 ID 并更新所选记录:
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();
}
但它不会更新记录。
我想也许 row.id 返回字符串,ID 数据类型是 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
要将字符串转换为
ObjectId
,请使用 ObjectId.Parse(string) 方法。还尝试匹配
"_id"
而不是"ID"
。所以像这样:
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:
在为 ObjectID 设置公共属性时,我遇到了同样的问题。
我的属性使用以下代码片段将 ObjectID 转换为字符串,然后再转换回 ObjectID。
ObjectID 没有作为一个选项出现,所以我必须使用完整的命名空间,像这样
MongoDB.Bson.ObjectId.Parse
访问.Parse()
希望这有帮助!
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 thisMongoDB.Bson.ObjectId.Parse
Hope this helps!
我发现的最简单的方法是使用:
new ObjectId(yourString)
...这将从字符串中为您提供一个 MongoDB ObjectId,并且应该适用于您的任何查询。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.您只需要从 mongo 中获取 ObjectId 函数即可。
然后你可以像这样使用它:
所以你可以将代码行更改为:
You just need to require the ObjectId function from your mongo.
Then you can use it like that:
So you can change your line of code to:
另一种方法是:
Another way is:
如果你用mgo,你可以试试这个
if you use mgo, you can try this one