Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upsert with counter

Tags:

mongodb

upsert

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?

like image 618
tajji Avatar asked Feb 12 '26 09:02

tajji


1 Answers

You can use bulkWrite

$inc

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 } }
        }
    }
])
like image 71
Tushar Gupta - curioustushar Avatar answered Feb 15 '26 00:02

Tushar Gupta - curioustushar