skip to Main Content

I am building nodejs application and I am using MongoDB official driver(not mongosse)

And I want to write a command to MongoDB.

I have 100 documents in a collection. (All id’s are unique )

I want keep the first 50 documents and delete all other documents in the collection

That means skip the first 50 documents and delete all other documents

What command should I write.

2

Answers


  1. Chosen as BEST ANSWER

    I had 100 documents.

    I manage to skip the first 50 documents and return other 50 documents ids with this command in nodejs

    const readDb = client.db(db).collection(colName);
    
    const result = (await readDb.find({}, { projection: { _id: 1 } }).skip(50).toArray()).map(doc => doc._id);
    

    The result was

    result = ['6312bdd5cd935206f3dc3b93','6312bdd50b68ed5d5df1a374','6312bdd531d11e0a3b58c96a','6312bdd58a0838f92fa2da21','6312bdd539fd4bdf799a6af4',]
    

    (Not all 50 documents ids are here. But it will return all 50 ids)

    Then I deleted the 50 documents with this command

    const deleteDb = client.db(db).collection(colName);
    await deleteDb.deleteMany({ _id: { $in: result });
    

    I hope this is clear


  2. On the mongo-shell you can try this if you want to order and delete by specific field:

    db.collection.remove({_id: 
        { $in: db.collection.find({}).sort({timestamp:-1}).skip(50).map(doc => doc._id) }
    })
    

    If you simply want to delete and keep them, according to the insertion order, remove the sort command:

    db.collection.remove({_id: 
        { $in: db.collection.find({}).skip.(50).map(doc => doc._id) }
    })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search