I have a table in database (MongoDB) that stores one id field as a string but it is a integer number (for example, original 12 -> in table '12'). Now I need to get a maximum value on this field but maximum at the context that this number is integer. Please, give me solution how to do it? (I can't change type of field in table)
Asked
Active
Viewed 604 times
0
-
Possible duplicate of [how to convert string to numerical values in mongodb](https://stackoverflow.com/questions/29487351/how-to-convert-string-to-numerical-values-in-mongodb) – dnickless Oct 04 '18 at 21:05
2 Answers
0
One possible way to do this is with aggregation:
db.collectionName.aggregate([{
$convert: {
input: "$intButStringKey",
to: "int"
}
}, {
maxValue: {
$max: "$intButStringKey"
}
}])

Atish
- 4,277
- 2
- 24
- 32
0
If you are on MongoDb 4.0 and up you can simply use $toInt in something like this:
db.collection.aggregate([
{
$group: {
"_id": "MYFIELD",
"Max": {
"$max": {
"$toInt": "$MYFIELD"
}
}
}
}
])
OR you can also use $convert:
db.collection.aggregate([
{
$group: {
"_id": "MYFIELD",
"Max": {
"$max": {
"$convert": { "input": "$MYFIELD", "to": "int" }
}
}
}
}
])
You could also use $addFields to add that int field early in your aggregation:
db.collection.aggregate([
{
$addFields: {
intField: {
$toInt: "$MYFIELD"
}
}
},
{
$group: {
_id: "$max",
max: {
$max: "$intField"
}
}
},
{
$project: {
_id: 0
}
}
])

Akrion
- 18,117
- 1
- 34
- 54