Compartilhar via


$convert

APLICA-SE A: MongoDB vCore

O operador $convert converte uma expressão em um valor do tipo especificado. O operador $convert também executará uma ação especificada se a conversão da expressão de entrada para o tipo especificado falhar.

Sintaxe

A sintaxe do $convert operador é:

{ "$convert": {"input": <expression>, "to": <type>, "format": <binData format>, "onError": <value to return on error>, "onNull": <value to return on null> }

Parâmetros

Parâmetro Descrição
input O valor de entrada a ser convertido no tipo especificado
to O tipo para o qual o valor de entrada será convertido
format (Opcional) O formato binData da entrada ou saída ao converter um valor de ou para binData
onError (Opcional) O valor a ser retornado quando a conversão da entrada para o tipo especificado falhar
onNull (Opcional) O valor a ser retornado quando o valor de entrada a ser convertido no tipo especificado for nulo ou ausente

Exemplos

Considere este documento de exemplo da coleção de lojas no banco de dados StoreData.

{
    "_id": "0fcc0bf0-ed18-4ab8-b558-9848e18058f4",
    "name": "First Up Consultants | Beverage Shop - Satterfieldmouth",
    "location": {
        "lat": -89.2384,
        "lon": -46.4012
    },
    "staff": {
        "totalStaff": {
            "fullTime": 8,
            "partTime": 20
        }
    },
    "sales": {
        "totalSales": 75670,
        "salesByCategory": [
            {
                "categoryName": "Wine Accessories",
                "totalSales": 34440
            },
            {
                "categoryName": "Bitters",
                "totalSales": 39496
            },
            {
                "categoryName": "Rum",
                "totalSales": 1734
            }
        ]
    },
    "promotionEvents": [
        {
            "eventName": "Unbeatable Bargain Bash",
            "promotionalDates": {
                "startDate": {
                    "Year": 2024,
                    "Month": 6,
                    "Day": 23
                },
                "endDate": {
                    "Year": 2024,
                    "Month": 7,
                    "Day": 2
                }
            },
            "discounts": [
                {
                    "categoryName": "Whiskey",
                    "discountPercentage": 7
                },
                {
                    "categoryName": "Bitters",
                    "discountPercentage": 15
                },
                {
                    "categoryName": "Brandy",
                    "discountPercentage": 8
                },
                {
                    "categoryName": "Sports Drinks",
                    "discountPercentage": 22
                },
                {
                    "categoryName": "Vodka",
                    "discountPercentage": 19
                }
            ]
        },
        {
            "eventName": "Steal of a Deal Days",
            "promotionalDates": {
                "startDate": {
                    "Year": 2024,
                    "Month": 9,
                    "Day": 21
                },
                "endDate": {
                    "Year": 2024,
                    "Month": 9,
                    "Day": 29
                }
            },
            "discounts": [
                {
                    "categoryName": "Organic Wine",
                    "discountPercentage": 19
                },
                {
                    "categoryName": "White Wine",
                    "discountPercentage": 20
                },
                {
                    "categoryName": "Sparkling Wine",
                    "discountPercentage": 19
                },
                {
                    "categoryName": "Whiskey",
                    "discountPercentage": 17
                },
                {
                    "categoryName": "Vodka",
                    "discountPercentage": 23
                }
            ]
        }
    ]
}

Exemplo 1: converter um valor int em uma cadeia de caracteres

db.stores.aggregate([
{
    "$match": {
        "_id": "b0107631-9370-4acd-aafa-8ac3511e623d"
    }
},
{
    "$project": {
        "fulltimeStaff": "$staff.totalStaff.fullTime",
        "fulltimeStaffAsString": {
            "$convert": {
                "input": "$staff.totalStaff.fullTime",
                "to": "string"
            }
        }
    }
}])

Essa consulta retorna o seguinte resultado:

{
    "_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
    "fulltimeStaff": 3,
    "fulltimeStaffAsString": "3"
}

Exemplo 2: converter um valor int em um valor booliano

db.stores.aggregate([
{
    "$match": {
        "_id": "b0107631-9370-4acd-aafa-8ac3511e623d"
    }
},
{
    "$project": {
        "fulltimeStaff": "$staff.totalStaff.fullTime",
        "fulltimeStaffAsBool": {
            "$convert": {
                "input": "$staff.totalStaff.fullTime",
                "to": "bool"
            }
        }
    }
}])

Essa consulta retorna o seguinte resultado:

{
    "_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
    "fulltimeStaff": 3,
    "fulltimeStaffAsBool": true
}

Exemplo 3: converter um valor int em um valor decimal

db.stores.aggregate([
{
    "$match": {
        "_id": "b0107631-9370-4acd-aafa-8ac3511e623d"
    }
},
{
    "$project": {
        "fulltimeStaff": "$staff.totalStaff.fullTime",
        "fulltimeStaffAsDecimal": {
            "$convert": {
                "input": "$staff.totalStaff.fullTime",
                "to": "decimal"
            }
        }
    }
}])

Essa consulta retorna o seguinte resultado:

{
    "_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
    "fulltimeStaff": 3,
    "fulltimeStaffAsDecimal": "Decimal128('3')"
}

Exemplo 4: Converter um valor int em um valor Long

db.stores.aggregate([
{
    "$match": {
        "_id": "b0107631-9370-4acd-aafa-8ac3511e623d"
    }
},
{
    "$project": {
        "fulltimeStaff": "$staff.totalStaff.fullTime",
        "fulltimeStaffAsLong": {
            "$convert": {
                "input": "$staff.totalStaff.fullTime",
                "to": "long"
            }
        }
    }
}])

Essa consulta retorna o seguinte resultado:

{
    "_id": "b0107631-9370-4acd-aafa-8ac3511e623d",
    "fulltimeStaff": 3,
    "fulltimeStaffAsLong": "Long('3')"
}