Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Spring MongoDb Update nested object

Hello I would like use this mongo query in spring to change type fields from string to double:

db.getCollection("data").update(
    {
        "location.latitude": { $type: 2 },
        "location.longitude": { $type: 2 }
    },
    [{
        $set: {
            "location.latitude": { $toDouble: "$geolocation.latitude" },
            "location.longitude": { $toDouble: "$geolocation.longitude" }
        }
    }]
)

Model:

data class Data(
    @Id
    val id: ObjectId,
    val location: Location,
)

My code in spring:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

mongoTemplate.updateMulti(
            Query()
                .addCriteria(Criteria.where("data.latitude").`is`("\$type:2"))
                .addCriteria(Criteria.where("data.longitude").`is`("\$type:2")),
            Update()
                .set("location.latitude", ConvertOperators.ToDouble.toDouble("\$location.latitude"))
                .set("location.longitude", ConvertOperators.ToDouble.toDouble("\$location.longitude")),
            "data"
        )

but its generate something like that:

db.getCollection("data").update(
    {
        "location.latitude": "$type:2",
        "location.longitude": "$type:2"
    },
    {
        "$set": {
            "location.latitude": { "$toDouble": "$geolocation.latitude" },
            "location.longitude": { "$toDouble": "$geolocation.longitude" }
        }
    }
)

but its not correct

>Solution :

You need to use type function in spring not is to check type

Reference

Criteria.where("data.latitude").type(2)

For the second problem, As @YongShun pointed out you need to use AggregationUpdate

AggregationUpdate.update()
    .set("location.latitude", ConvertOperators.ToDouble.toDouble("\$location.latitude"))
    .set("location.longitude", ConvertOperators.ToDouble.toDouble("\$location.longitude"))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading