how to use $addToSet and $inc value of the set item in MongoDB
Try this one:
var newEvent = "e2"
db.collection.aggregate([
{
$set: {
events: {
$cond: {
if: { $in: [newEvent, "$events.eventName"] },
then: {
$map: {
input: "$events",
as: "event",
in: { $mergeObjects: ["$$event", { times: { $add: ["$$event.times", 1] } }] }
}
},
else: { $concatArrays: ["$events", [{ eventName: newEvent, "times": 0 }]] },
}
}
}
}
])