I have a fruit collection with the following documents:
{
tag: "Apple",
count: 3
},
{
tag: "Banana",
count: 2
}
I get new documents with tags and values. Value 1 meaning increase the counter, and value -1 meaning decrease the counter
{
tag: "Coconut",
value: 1
},
{
tag: "Banana",
count: -1
}
The result of the upsert should be:
{
tag: "Apple",
count: 3
},
{
tag: "Banana",
count: 1 // previously 2, decrease counter by 1
},
{
tag: "Coconut",
count: 1 // Did not exist, so add and set counter to 1
}
Also, if a count decreases to 0 (or less), remove the document from the collection.
So if I get this next:
{
tag: "Apple",
count: 1
},
{
tag: "Banana",
count: -1
}
The result of this next upsert should be
{
tag: "Apple", // previously 3, increase by 1
count: 4
},
// {
// tag: "Banana",
// count: 0 // Remove from collection
// },
{
tag: "Coconut",
count: 1
}
How do I achieve this in a concise way in mongodb?