英文:
How do I convert String to an Object in MongoDB?
问题
在我的Mongo数据库中,我有一个名为“Books”的集合,其中有一个名为“category”的字段。在过去,“category”是在Mongo中映射为String的枚举,但现在我需要将“category”作为“Books”集合内的一个对象。我该怎么做?是否有一条查询可以一次性地转换所有文档?
例如,今天的category是这样的:
"category" : "科幻和奇幻"
但我需要转换成这样:
"category" : {
"_id" : ObjectId("3f07bc56po324021df23a8f1"),
"code" : NumberLong(1),
"name" : "科幻和奇幻"
}
英文:
In my Mongo database, I have a "Books" collection with a "category" field. In the past, "category" was an enum mapped as String in Mongo but now I need "category" to be an object within my "Books" collection. What can I do? Is there a query that can be executed to convert all documents at once?
Example, today category is like that:
"category" : "Sci-Fi and Fantasy"
But I need to convert to this:
"category" : {
"_id" : ObjectId("3f07bc56po324021df23a8f1"),
"code" : NumberLong(1),
"name" : "Sci-Fi and Fantasy"
}
答案1
得分: 1
MongoDB是一个NoSQL数据库,你的Mongo集合中可以同时包含两种类型的记录,尽管在读取记录时,你可能需要构建一些逻辑来创建相同的实体。如果你基于该特定属性进行搜索,这可能会引起问题。
你可以创建一个新的属性,使用不同的名称,同时保留类别,并将新属性添加到所有记录中。
英文:
MongoDB is no SQL you can have both kind of records present in your mongo collection, although while reading the records you might have to frame some logic for creating identical entities. This might cause issues if you search based on that particular property.
You can create a new property with different name keeping the category as well and then add the new property to all the records.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论