Spring MongoDb 更新嵌套对象

Spring MongoDb Update nested object

您好,我想在 spring 中使用此 mongo 查询将类型字段从字符串更改为双精度:

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

型号:

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

我的代码在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"
        )

但它会生成类似的东西:

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

但不正确

您需要在 spring 而不是 is 中使用 type 函数来检查 type

Reference

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

对于第二个问题,正如@YongShun指出的那样,你需要使用AggregationUpdate

AggregationUpdate.update()
    .set("location.latitude", ConvertOperators.ToDouble.toDouble("$location.latitude"))
    .set("location.longitude", ConvertOperators.ToDouble.toDouble("$location.longitude"))