Reputation: 465
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?
Upvotes: 3
Views: 411
Reputation: 57105
You can use bulkWrite
db.myCollection.bulkWrite([
{
updateOne: {
filter: { tag: "Banana" } ,
update: { $inc: { "count": -1 } },
upsert : true
}
},
{
updateOne: {
filter: { tag: "Coconut" } ,
update: { $inc: { "count": 1 } },
upsert: true
}
},
{
deleteMany : { // delete records records if count is 0 or less
filter : { count: { $lte: 0 } }
}
}
])
Upvotes: 1