mongodb 如何将字符串转换为 ObjectId

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8503673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 12:22:28  来源:igfitidea点击:

How to convert string into ObjectId

mongodbmongodb-.net-driver

提问by user768853

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

我正在从 MongoDB 获取数据并绑定到 WPF 数据网格。

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

我的代码选择多行,检索 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();
}

But it does not update the record.

但它不会更新记录。

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

我想也许 row.id 正在返回字符串,而 ID 数据类型是 objectId。

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

除上述情况外,此查询适用于其他数据类型。

回答by Zaid Masud

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

要将字符串转换为ObjectId,请使用ObjectId.Parse(string)方法。

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

还尝试匹配 on"_id"而不是"ID"

So something like:

所以像:

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

回答by Brian J

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

我在为 ObjectID 设置公共属性时遇到了同样的问题。

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

我的属性使用以下代码片段将 ObjectID 转换为字符串,然后返回为 ObjectID。

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

ObjectID 没有作为一个选项出现,所以我必须使用完整的命名空间,来访问.Parse()这样的MongoDB.Bson.ObjectId.Parse

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

Hope this helps!

希望这可以帮助!

回答by SaltySub2

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.

我发现的最简单的方法是使用:new ObjectId(yourString)...这将为您提供一个字符串中的 MongoDB ObjectId,并且应该可以处理您的任何查询。

回答by julien bouteloup

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

您只需要从您的 mongo 中要求 ObjectId 函数。

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