更新文档中嵌入的特定记录
Update Specific Record Embedded In document
这是我第一次使用 MongoDB 和 Spring-data-mongo。
有一个Company
对象
@Document
public class Company {
@Id
private String id;
private String name;
private String registrationNumber;
private List<Vehicle> vehicles;
}
public class Vehicle {
private String vehicleOwner;
@Indexed(unique = true)
private String plateNumber;
private Double speedLimit;
private GeoJsonPoint currentLocation;
}
我想为具有给定 plateNumber
的车辆更新 currentLocation
字段
很明显,我卡在这里了
mongoTemplate.find(Query.query(Criteria.where("vehicles"))), how to go to `plateNumber` field? And how to update `currentLocation` field for that particular matching `Vehicle` for the `Company`
这应该有效,构建查询以获取所需的文档,然后创建一个更新对象并填充值,如下所示,
Query query = new Query(Criteria.where("name").is("company_name")
.and("vehicles")
.elemMatch(Criteria.where("vehicleOwner").is("owner_name")));
Update update = new Update();
update.set("vehicles.$.plateNumber", "NEW NUMBER");
//You can use findAndModify or updateMulti based on your need.
mongoTemplate.updateFirst(query, update, Company.class);
您可以尝试更新 currentLocation
。
这是我第一次使用 MongoDB 和 Spring-data-mongo。
有一个Company
对象
@Document
public class Company {
@Id
private String id;
private String name;
private String registrationNumber;
private List<Vehicle> vehicles;
}
public class Vehicle {
private String vehicleOwner;
@Indexed(unique = true)
private String plateNumber;
private Double speedLimit;
private GeoJsonPoint currentLocation;
}
我想为具有给定 plateNumber
currentLocation
字段
很明显,我卡在这里了
mongoTemplate.find(Query.query(Criteria.where("vehicles"))), how to go to `plateNumber` field? And how to update `currentLocation` field for that particular matching `Vehicle` for the `Company`
这应该有效,构建查询以获取所需的文档,然后创建一个更新对象并填充值,如下所示,
Query query = new Query(Criteria.where("name").is("company_name")
.and("vehicles")
.elemMatch(Criteria.where("vehicleOwner").is("owner_name")));
Update update = new Update();
update.set("vehicles.$.plateNumber", "NEW NUMBER");
//You can use findAndModify or updateMulti based on your need.
mongoTemplate.updateFirst(query, update, Company.class);
您可以尝试更新 currentLocation
。