Estoy tratando de convertir todos los documentos en una colección mongo que tienen un campo configurado actualmente como Int64 a Int32.
Actualmente aquí está mi documento:
{ _id: ObjectId("60af668346895440fad766c2"), userId: 'xxxxxxxx', postName: 'testPost', numberOfComments: Long("3"), numberOfLikes: Long("6") }Como se indicó anteriormente, me gustaría cambiar numerbOfComments de Long (Int64) a Int32
Intenté usar varias formas (ver a continuación), pero solo cambia el tipo de datos en la salida y no modifica el documento en la base de datos.
¿Alguien puede ayudar por favor?
Lo que he probado hasta ahora
db.posts.aggregate( [ { $project: { result: { $convert: { input: "$numberOfComments", to: "int", onError: "An error occurred", onNull: "Input was null or empty" } } } } ] )También he probado esto:
db.posts.aggregate([ { $set: { numberOfComments: { toInt: '$numberOfComments' }, }, }, ], {multi: true}) db.posts.updateMany( { numberOfComments : { $type: Long } }, [{ $set: { numberOfComments: { $toInt: "$numberOfComments" } } }], { multi: true }) db.UserProjects.aggregate( [ { $project: { _id: 0, numberOfComments: { $toInt: "$numberOfComments" } } } ] ).pretty()Necesita usar la actualización agregada.
db.collection.update({ key: 3 //You can leave empty }, [ //aggregate update as you need $toInt { $set: { numberOfComments: { "$toInt": "$numberOfComments" } } } ])Puse un ejemplo de error en el patio de recreo. Si establece un valor válido, funcionará.
Explore la sección de opciones para actualizar uno o varios documentos.