将现有的MongoDB字符串属性转换为BSON :: ObjectId [英] Convert existing MongoDB string attribute to BSON::ObjectId

查看:152
本文介绍了将现有的MongoDB字符串属性转换为BSON :: ObjectId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在MongoDB中有一个文档集合,该文档的属性存储为字符串,如果将其另存为BSON :: ObjectId,效果会更好.

I have a collection of documents in MongoDB that has an attribute being stored as a string when it would work better if it was saved as BSON::ObjectId.

集合名称为foo,该字段称为bar.使每个字段bar将其现有值转换为BSON :: ObjectId的实例的最佳方法是什么?

The collection name is foo and the field is called bar. What's the best way to have every field bar turn its existing value into an instance of BSON::ObjectId?

推荐答案

这是您的意思吗? (您有一个字符串,它是一个ObjectId的十六进制,并且您想将其转换为一个ObjectId)

Is this what you mean? (You have a string that is the hex of an ObjectId, and you want to turn it into an ObjectId)

> db.foo.insert({bar:new ObjectId().str});
> db.foo.insert({bar:new ObjectId().str});
> db.foo.insert({bar:new ObjectId().str});
> db.foo.find();
{ "_id" : ObjectId("4f95e00d9060633ce7fbab94"), "bar" : "4f95e00d9060633ce7fbab93" }
{ "_id" : ObjectId("4f95e0119060633ce7fbab96"), "bar" : "4f95e0119060633ce7fbab95" }
{ "_id" : ObjectId("4f95e0119060633ce7fbab98"), "bar" : "4f95e0119060633ce7fbab97" }
> db.foo.find().forEach(function(doc) { db.foo.update({_id:doc._id},{$set:{bar:new ObjectId(doc.bar)}}); });
> db.foo.find();
{ "_id" : ObjectId("4f95e00d9060633ce7fbab94"), "bar" : ObjectId("4f95e00d9060633ce7fbab93") }
{ "_id" : ObjectId("4f95e0119060633ce7fbab96"), "bar" : ObjectId("4f95e0119060633ce7fbab95") }
{ "_id" : ObjectId("4f95e0119060633ce7fbab98"), "bar" : ObjectId("4f95e0119060633ce7fbab97") }

这是您的意思吗? (您有一个字符串,但您想将其吹走并在其位置创建一个新的ObjectId)

Or is this what you mean? (You have a string but you want to blow it away and create a new ObjectId in its place)

> db.foo.insert({bar:"some string id"});
> db.foo.insert({bar:"some string id2"});
> db.foo.insert({bar:"some string id3"});
> db.foo.find();
{ "_id" : ObjectId("4f95e1779060633ce7fbaba5"), "bar" : "some string id" }
{ "_id" : ObjectId("4f95e1799060633ce7fbaba6"), "bar" : "some string id2" }
{ "_id" : ObjectId("4f95e17b9060633ce7fbaba7"), "bar" : "some string id3" }
> db.foo.find().forEach(function(doc) { db.foo.update({_id:doc._id},{$set:{bar:new ObjectId()}}); });
> db.foo.find();
{ "_id" : ObjectId("4f95e1779060633ce7fbaba5"), "bar" : ObjectId("4f95e1819060633ce7fbaba8") }
{ "_id" : ObjectId("4f95e1799060633ce7fbaba6"), "bar" : ObjectId("4f95e1819060633ce7fbaba9") }
{ "_id" : ObjectId("4f95e17b9060633ce7fbaba7"), "bar" : ObjectId("4f95e1819060633ce7fbabaa") }

这篇关于将现有的MongoDB字符串属性转换为BSON :: ObjectId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆