如果我有一个mongo文件ID作为字符串我如何查询它作为_id? [英] If i have a mongo document id as a string how do I query for it as an _id?
问题描述
如果我有一个mongo文档id作为字符串,我该如何查询它作为_id?
If i have a mongo document id as a string how do I query for it as an _id?
它能正常工作 .find({_ id:'stringID'})
或者我是否需要先将其转换为bson对象?
Will it work correctly to do .find({_id:'stringID'})
or do I need to convert it to a bson object first?
推荐答案
你的意思是你有一个ObjectId的24位十六进制数字字符串吗?
Do you mean you have the 24 hex digit string of an ObjectId?
假设这就是你的意思,大多数司机都有办法取一个字符串并将其转换为ObjectId。在JavaScript中:
Assuming that's what you mean, most drivers have a way to take a string and convert it to an ObjectId. In JavaScript that's:
.find({_id:new ObjectId("4f91bfcfaa7c5687a0c686d4")})
已更新对节点本机驱动程序更有用(来自 https://github.com/christkv/node-mongodb-native ):
Updated to be a bit more useful for the node-native driver (from the documentation at https://github.com/christkv/node-mongodb-native):
// Get the objectID type
var ObjectID = require('mongodb').ObjectID;
var idString = '4e4e1638c85e808431000003';
collection.findOne({_id: new ObjectID(idString)}, console.log) // ok
collection.findOne({_id: idString}, console.log) // wrong! callback gets undefined
这篇关于如果我有一个mongo文件ID作为字符串我如何查询它作为_id?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!