(1) Mettre à jour (extraire) reply
élément de tableau :
Ce code mettra à jour le document ; qui supprime l'élément spécifique (sous-document) de la reply
tableau :
// 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) Requête d'agrégation pour obtenir la reply
documents :
db.topics.aggregate( [
{ $unwind: "$topic" },
{ $match: { "topic._topicId": topicId } },
{ $unwind: "$topic.reply" },
{ $match: { "topic.reply._replyId": topicReplyId } },
{ $project: { _id: 0, reply: "$topic.reply" } }
] ).pretty()
Cela renvoie :
{
"reply" : {
"_replyId" : "07a0293a-22a1-45fb-9aa2-775fa24e9915",
"username" : "test1",
"content" : "reply1",
"date" : 1583240955561
}
}