skip to Main Content

I want to delete some records after sort and skip items but this query always delete all records after find.as if sort and skip don’t do anything’:

await Book.find(Book.owner.id == user.id).sort("-created_at").skip(2).delete()

2

Answers


  1. Chosen as BEST ANSWER

    We can delete the items by beanie functionality like this:

    from app.models.book_model import Book
    from beanie.operators import In
    
    books= await Book.find(Book.owner.id == user.id).sort("-created_at").skip(2).to_list()
    
    books_del= Book.find(In(Book.id, [_.id for _ in books]))
    await books_del.delete()
    

  2. To achieve the target you can first fetch the docs by applying a skip function & then use deleteMany function.

    Note: You can also use sort({_id:-1}) to sort the docs.

    See the Example code below-

    const data = await Book.find(pass-your-query-here).sort({_id:-1}).skip(2);
            if(data.length>0){
              const ress = await Book.deleteMany({ _id: {$lte: data[0]._id } });
            }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search