简体   繁体   中英

MongoDB, how to create an empty collection?

How can I create an empty collection in MongoDB?

I've tried various things but they didn't work, that would be declaring it differently. What I know is that it should create a collection automatically when needed, but not sure.

However, you could technically create a collection and delete that what is inside.

This is an example on what I've tried:

function test() {
        db.createCollection("test", function() {});
        console.log("Collection has been created.")
};
test();

The following creates a collection for me and prints your log message:

function test() {
        db.createCollection("test");
        console.log("Collection has been created.")
};
test();

I removed the function(){} in your db.createCollection, maybe that caused your error?

In MongoDB no need to explicitly check if a collection already exists or not before doing any CRUD operations.

MongoDB will create the collections on the when it is required.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM