MongoDB: How To Delete All Records Of A Collection in MongoDB Shell?

后端 未结 5 1137
生来不讨喜
生来不讨喜 2021-01-30 15:23

I\'ve tried

db.users.remove(*)

Although it returns an error so how do I go about clearing all records?

相关标签:
5条回答
  • 2021-01-30 16:04

    The argument to remove() is a filter document, so passing in an empty document means 'remove all':

    db.user.remove({})
    

    However, if you definitely want to remove everything you might be better off dropping the collection. Though that probably depends on whether you have user defined indexes on the collection i.e. whether the cost of preparing the collection after dropping it outweighs the longer duration of the remove() call vs the drop() call.

    More details in the docs.

    0 讨论(0)
  • 2021-01-30 16:11
    db.users.count()
    db.users.remove({})
    db.users.count()
    
    0 讨论(0)
  • 2021-01-30 16:14

    To remove all the documents in all the collections:

    db.getCollectionNames().forEach( function(collection_name) { 
        if (collection_name.indexOf("system.") == -1) {
            print ( ["Removing: ", db[collection_name].count({}), " documents from ", collection_name].join('') );
            db[collection_name].remove({}); 
        }
    });
    
    0 讨论(0)
  • 2021-01-30 16:18

    Delete all documents from a collection in cmd:

    cd C:\Program Files\MongoDB\Server\4.2\bin
    mongo
    use yourdb
    db.yourcollection.remove( { } )
    
    0 讨论(0)
  • 2021-01-30 16:25

    You can delete all the documents from a collection in MongoDB, you can use the following:

    db.users.remove({})
    

    Alternatively, you could use the following method as well:

    db.users.deleteMany({})
    

    Follow the following MongoDB documentation, for further details.

    To remove all documents from a collection, pass an empty filter document {} to either the db.collection.deleteMany() or the db.collection.remove() method.

    0 讨论(0)
提交回复
热议问题