Home > front end >  delete records from mongodb collection after skip by beanie ODM
delete records from mongodb collection after skip by beanie ODM

Time:12-04

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()

CodePudding user response:

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 } });
        }

CodePudding user response:

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()
  • Related