英文:
Using UpdateMany to Add a New Field With The Value of Another Field as a String
问题
我试图向我的所有文档添加一个新字段,该字段包含一个数字字段的值,但该值以字符串形式表示(以进行字段重命名和类型更改的尝试)。
我尝试了这个:
db.person.updateMany({}, {$set: { userId: {$toString:"$snowflake"} }})
这给了我这个:
我还尝试过仅仅这样做:
db.person.updateMany({}, {$set: { userId:"$snowflake" }})
这只是将该值插入为"$snowflake"。根据我所见,使用现有字段的方式似乎是正确的,我做错了什么吗?
MongoDB 6.0.6 Enterprise
英文:
I'm trying to add a new field to all of my documents that contains the value of a number field, but as a string instead (in an effort to do both a rename and a type change for that field).
I tried this:
db.person.updateMany({}, {$set: { userId: {$toString:"$snowflake"} }})
Which gave me this:
I've also tried just doing this:
db.person.updateMany({}, {$set: { userId:"$snowflake" }})
Which just inserted the value as "$snowflake". Everything I've seen suggests using existing fields this way, is there something I'm doing wrong?
MongoDB 6.0.6 Enterprise
答案1
得分: 1
在您的查询中,$toString
被视为一个字段,因为它没有在聚合管道 []
中使用,因此会创建一个包含 $toString
作为字段的 userId
对象。
解决方案
将您的查询更新为:
db.person.updateMany(
{},
[
{
$set: {
userId: { $toString: "$snowflake" }
}
}
]
)
英文:
The $toString
in your query as a field because it is not used within an aggregation pipeline []
, hence creating an userId
as an object with $toString
as a field in it.
Solution
Update your query as:
db.person.updateMany(
{},
[
{
$set: {
userId: { $toString: "$snowflake" }
}
}
]
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论