[英]How to write a query to delete an object from my MongoDB database in Springboot?
[英]Springboot MongoDB delete an object from array of objects
我正在尝试从mongodb
集合中的对象数组中删除 object 。 我已经遵循了 SO 的多个答案,但我无法让它发挥作用。
customer_id
和address_pin
将从查询字符串传递。 我想从address_india
中删除 object,其中address_pin
与通过查询字符串传递的值匹配。
MongoDB collection object
{
"_id":{
"$oid":"61fa7de3b3de485b30403c56"
},
"customer_id":"c7e690cf-c8d9-4a7b-b146-ade742958452",
"customer_addresses":{
"address_india":[
{
"address_id":"ccc428bd-3e4d-49e5-8569-ebacb181ad1e",
"address_pin":"MD0BuCQUxT", // I've to remove this object
"address_type":"sales"
},
{
"address_id":"ccc428bd-3e4d-49e5-8569-ebacb181asdf",
"address_pin":"MD0BuCQUXy",
"address_type":"marketing"
}
]
},
"create_timestamp":{
"$numberLong":"1643806179346"
},
"modified_timestamp":{
"$numberLong":"1643806179346"
}
}
Controller
return new ResponseEntity<CustomerAddressResponse>(
this.customerAddressService.deleteCustomerAddressById(customerId),
HandleResponseHeader.getResponseHeaders(UUID), HttpStatus.OK);
ServiceImpl
@Override
public CustomerAddressResponse deleteCustomerAddressById(String customerId)
throws Exception {
try {
if (isValidUUID(customerId)) {
Date now = new Date();
Long dateStartTime = now.getTime();
Stopwatch stopWatch = Stopwatch.createStarted();
CustomerAddress customerAddress = customerAddressDao
.findByCustomerId(customerId);
String pin = httpServletRequest.getParameter("address_pin")
.trim();
Query query = new Query();
query.addCriteria(Criteria.where("customer_id")
.is(customerId)
.and("customer_addresses.address_india")
.elemMatch(Criteria.where("address_pin").is(pin)));
Update update = new Update();
update.pull("customer_addresses.address_india", new Query().addCriteria(Criteria.where("address_pin").is(pin)));
FindAndModifyOptions options = FindAndModifyOptions.options();
options.returnNew(true);
MongoTemplate template = null;
template.findAndModify(query, update, options, CustomerAddress.class);
}
}
}
我在template.findAndModify(query, update, options, CustomerAddress.class);
收到java.lang.NullPointerException
如何从springboot
的mongodb
中的对象数组中删除 object ?
这是您从 mongo js shell 对单个文档执行的操作,它可能会给您一些关于如何从 springboot 执行的想法:
db.collection.update(
{
"customer_id": "c7e690cf-c8d9-4a7b-b146-ade742958452"},
{
$pull: {
"customer_addresses.address_india": {
"address_pin": "MD0BuCQUxT"
}
}
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.