Node Driver - How to updateMany Replace Array with last item in Array

I have a document with a Array called ‘lastLogin’ which has all the recent timestamps.

I would like to overwrite this array with a single element being the last index value in the array.

from
{
lastLogin : [timestamp1,timestamp2,timestamp3]
}

to

{
lastLogin : timestamp3
loginTimes : 3
}

So overwrite the lastLogin array with a single value of the last index
Add a field called loginTimes which is the total count of the lastLogin Array. (edited)

Not sure exactly how to do this either using aggregation or normal commands.

Tks.

Hi @Rishi_uttam,

I made this aggregation pipeline and I think it gets the job done.

[
  {
    '$unwind': {
      'path': '$lastLogin'
    }
  }, {
    '$group': {
      '_id': '$_id', 
      'lastLogin': {
        '$last': '$lastLogin'
      }, 
      'loginTimes': {
        '$sum': 1
      }
    }
  }, {
    '$merge': {
      'into': 'coll', 
      'on': '_id', 
      'whenMatched': 'merge', 
      'whenNotMatched': 'fail'
    }
  }
]

Test it before running in prod because it overwrites the lastLogin field as you requested. But you could also write the $last value into another field just to be safe if you prefer.

Cheers,
Maxime.

1 Like

wow thank you, thats great… i will test it out…

would the same be possible without using aggregation and mongo query language? i…e updateMany with $set?

Humm maybe but I’m not sure. At least this is its equivalent and I don’t know if the version without the aggregation pipeline is possible. At least I have no idea how I would do it if it’s even possible. Why is this important?

Ahh you mean using normal query language without aggregation may not be possible in one single operation?

i would like to learn actually how to do it without aggregation as im not to familiar with aggregation at this point, but thanks so much.

Rishi

Then this course was especially designed for you! And it’s free :tada: !

I don’t even know how to reuse the value of an existing field in the document without the aggregation framework. Maybe there is a way but the aggregation framework is really like super powers!

Using MongoDB without the aggregation framework is like using a motorbike without putting gas in it. :smiley: ! You will eventually be able to get to your destination but this is going to require a lot more effort and it won’t be efficient :slight_smile:.

I did some research before sending this answer and there is a way to do this with an “update” operation. But you will also need the aggregation pipeline which can now be used in the update operations… :muscle:. So it’s aggregation or aggregation basically.

Cheers,
Maxime.

2 Likes

Hi, Thanks I already started the course, and hope to learn a lot from it.

I did not know that agg framework can also update, insert data, i thought it was for reading data only.

1 Like

You have the list of all the stages here.

$out and $merge can write data into a collection. :slight_smile: