(1) Update (pull) reply
array-element:
Deze code werkt het document bij; dat wil zeggen het verwijdert het specifieke element (subdocument) uit het reply
reeks:
// Query criteria for topic and reply
String topicId = "5e5e4d4bb431502946c15342";
String topicReplyId = "07a0293a-22a1-45fb-9aa2-775fa24e9915";
MongoOperations mongoTemplate = new MongoTemplate(MongoClients.create(), "test");
Query query = Query.query(Criteria
.where("topic._topicId").is(topicId)
.and("topic.reply._replyId").is(topicReplyId));
Update update = new Update().pull("topic.$.reply", new Document("_replyId", topicReplyId));
mongoTemplate.updateFirst(query, update, "topics"); // "topics" is the collection name
(2) Aggregatiequery om het reply
te krijgen document:
db.topics.aggregate( [
{ $unwind: "$topic" },
{ $match: { "topic._topicId": topicId } },
{ $unwind: "$topic.reply" },
{ $match: { "topic.reply._replyId": topicReplyId } },
{ $project: { _id: 0, reply: "$topic.reply" } }
] ).pretty()
Dit geeft als resultaat:
{
"reply" : {
"_replyId" : "07a0293a-22a1-45fb-9aa2-775fa24e9915",
"username" : "test1",
"content" : "reply1",
"date" : 1583240955561
}
}