In my project, I am using Spring Boot and MongoDB.
I would like to remove object from list in JSON by objectId
:
I have a profile object in the database that looks like this:
{
"_id" : ObjectId("61c05611a8237a39811ec3c0"),
"runningStyle" : [
{
"_id" : ObjectId("61c05616a8237a39811ec3c1"),
"name" : "name1",
"priority" : "priority1",
"average" : "1"
},
{
"_id" : ObjectId("61c05616a8237a39811ec3c2"),
"name" : "name2",
"priority" : "priority2",
"average" : "2"
},
{
"_id" : ObjectId("61c05616a8237a39811ec3c3"),
"name" : "name3",
"priority" : "priority3",
"average" : "3"
}
]
}
I would like to remove object
by its ID
in list runningStyle
in Profile object.
This is what I have tried in code:
RunningController.java
@DeleteMapping(value = "/delete/{runningStyleId}")
public void deleteRunningStyle(@PathVariable String runningStyleId){
playingStyleService.deletePlayingStyle(playingStyleId);
}
RunningServiceImpl.java
@Override
public void deletePlayingStyle(String playingStyleId) {
profile.ifPresent(up -> savedPlayingStyle.ifPresent(sps -> {
up.getPlayingStyle().stream().filter(am -> am.getId().equals(playingStyleId))
.findFirst()
.ifPresent(ps -> profileRepository.deleteById(ps.getId()));
playingStyleRepository.deleteById(playingStyleId);
}));
}
With this code, I don't have any error, but object is not deleted from list in my Profile.
I have also tried by adding something like this in repository:
@Query(value = "{ '_id' : { '$oid' : ?0}}", delete = true)
void deleteRunningStyleById(String runningStyleId);
But it is not deleting it.
What am I doing wrong? What is the best way to achieve this?
UPDATE
I have added:
@Query(value = "{'$pull': {'runningStyle':{'_id' : ?0 }}}", delete = true)
void deleteRunningStyleById(String runningStyleId);
But I am getting following error:
unknown top level operator: $pull. If you have a field name that starts with a '$' symbol, consider using $getField or $setField.
@Autowired
private MongoTemplate mongoTemplate;
...
@Override
public void deletePlayingStyle(String playingStyleId) {
Update update = new Update();
// $pull
update.pull("runningStyle", new Document("_id", new ObjectId(playingStyleId)));
//UpdateResult { "acknowledged" : true, "matchedCount" : x, "modifiedCount" : y }
//check if modifiedCount > 0 to make sure profile updated
mongoTemplate.updateMulti(new Query(), update, Profile.class);
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.