Skip first document during update

I want to write a query to update all documents based on a condition but skip the very first one. So far I’ve come with the following query:

collection.find( { field1: "abc" }).sort( { date: -1 } ).skip( 1 ).update( [ { $set: { old: true } } ] )

I’m expecting this to

  1. find the documents based on the condition
  2. sort them based on date
  3. skip the first one
  4. update the rest and set the old filed to true

However, when I run this it updates all the documents matching the “find” condition and does not skip the first one.

What am I doing wrong?
I’d appreciate any help with any other approach that has the same outcome as I’m looking for.

Hello @peter_g,

The collection’s find function returns a cursor. So, you are applying the sort and skip operations on the cursor correctly (those are cursor methods). But, your update operation is to be on the collection’s documents. That may be the reason why you are seeing an incorrect behaviuor.

You can try one of these following approaches for a correct result:

const docs = collection.find().sort().skip().forEach(doc => collection.updateOne( { _id: doc._id }, { $set: { old: true } } ) )


const ids_to_update = collection.find().sort().skip().map(doc => doc._id)
collection.updateMany( { _id: { $in: ids_to_update } }, { $set: { old: true } } )