mongodbmongodb-queryspring-dataspring-mongodb

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:

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"))