在 MongoDB 中将字符串转换为 ObjectID

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7825700/
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:16:53  来源:igfitidea点击:

Convert string to ObjectID in MongoDB

codeignitermongodb

提问by Jonathan Clark

I am developing an API using Codeigniter and MongoDB. In some parts of the database I have saved the ID of an image in ObjectID format instead of a string. Now I got an ID in string format and I need to query the database using it.

我正在使用 Codeigniter 和 MongoDB 开发 API。在数据库的某些部分中,我以 ObjectID 格式而不是字符串保存了图像的 ID。现在我得到了一个字符串格式的 ID,我需要使用它来查询数据库。

How can I "convert" a string to an ObjectID so that I can do the query?

如何将字符串“转换”为 ObjectID 以便进行查询?

From this:

由此:

34234234234234234234

To this:

对此:

ObjectID("34234234234234234234")

UPDATE

更新

I found a solution. Just do this new MongoId('34234234234234234234');

我找到了解决方案。就这样做new MongoId('34234234234234234234');

采纳答案by Konstantin Yovkov

http://api.mongodb.org/java/2.6.5/org/bson/types/ObjectId.html

http://api.mongodb.org/java/2.6.5/org/bson/types/ObjectId.html

Here, you can see that there is a constructor ObjectId with single String parameter. So, can't it be useful to you ?

在这里,您可以看到有一个带有单个 String 参数的构造函数 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("34234234234234234234")

回答by Nicolas Del Valle

Using mongoose:

使用猫鼬:

var mongoose = require('mongoose');
var objectId = mongoose.Types.ObjectId('569ed8269353e9f4c51617aa');

Using native driver (https://stackoverflow.com/a/21076589/3377073)

使用本机驱动程序(https://stackoverflow.com/a/21076589/3377073

var ObjectId = require('mongodb').ObjectId;
doc._id = new ObjectId(doc._id); // wrap in ObjectID

回答by Alex K

If you are using Meteor

如果您使用流星

var id = new Mongo.ObjectID("34234234234234234234");

回答by Manna

or better use

或更好地使用

var mongodb = require(‘mongodb'); //this might have been defined at the beginning of your code.
//now use it
query = {_id:mongodb.ObjectId('569ed8269353e9f4c51617aa')};

and the rest is the same.

其余的都是一样的。

回答by Carlos

you can now convert string to objectId on mongodb 4.0 and above. there is new feature to convert from string id to objectId

您现在可以在 mongodb 4.0 及更高版本上将字符串转换为 objectId。有一个新功能可以将字符串 id 转换为 objectId

here you can see the documentation $toObjectId

在这里你可以看到文档$toObjectId