My objective is to change the type of some fields in my documents over my full collection. I want to change some strings to int using $toInt.
I am trying to update the '$helpful' field to be an integer. Here is what my schema looks like in an example document:
_id: ObjectId("62e32a75a984c054fb986fbf"),
id: '7',
product_id: '2',
body: 'Where is this product made?',
date_written: '1590428073460',
asker_name: 'iluvcatz',
asker_email: 'first.last@gmail.com',
reported: '0',
helpful: '0',
answers: [ ]
When I run this command:
db.question.updateMany({ }, [{ $set: { "helpful": {$toInt: "$helpful"}}}])
I get the following error message:
MongoServerError: Failed to parse number 'helpful' in `$convert` with no onError value: Did not consume whole string.
I have tried modifying my command to change my first parameter of updateMany
to filter for things that would include all my helpful
field values, like:
{helpful: {$exists: true}}
{helpful: {$type: "string"}}
When I try this as my filter and specify it exactly it works:
{helpful: "0"}
But I have many different string values 0-100 for my helpful field. Any idea why this isn't working?
The error throws because some of the documents have alphabets or special symbols like dot .
, You can check the examples when $toInt
will throw an error .
There is another operator $convert , I would suggest you use that because it handles error and null values,
onError
if it throws an error,onNull
if the value has null
valuedb.question.updateMany(
{},
[{
$set: {
helpful: {
$convert: {
input: "$helpful",
to: "int",
onError: null, // Optional.
onNull: null // Optional.
}
}
}
}]
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.