Mongodb create collection if not exists python

Previous: Python MongoDB Creating a Collection

Checking if a Collection Exists in MongoDB

In the previous articles, we have created our "firstdatabase" and added the collection "Programming Languages" to the database. To print all the collection names in our database we will use the list_collection_names() method of the Database class.

Remember to initialize the MongoDB before running the script below:

import pymongo

client = pymongo.MongoClient("mongodb://localhost:27017/")
mydb = client[
"firstdatabase"]

mycol = mydb['Programming Languages']

print(mydb.list_collection_names())

col_name = 'Programming Languages'
if col_name in mydb.list_collection_names():
print(
True)
else:
print(
False)

Once we add some data to our collection "Programming Languages", we will be able to see the name of the collection in the output. In the next article, we will insert "documents" i.e. records in our collection.

Next: Python MongoDB Insert Into Collection

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Using drop() method we can drop collection if collection exists. If collection is not found then it returns False otherwise it returns True if collection is dropped. 

    Syntax:

    drop()

    Example 1: 

    The sample database is as follows: 

    Mongodb create collection if not exists python
     

    Python3

    Output: 

    Mongodb create collection if not exists python

    Example 2: If collection does not exist. 
     

    Python3

    import pymongo

    db = client["mydatabase"]

    col = db["gfg"]

    if col.drop():

        print('Deleted')

    else:

        print('Not Present')

    Output:

    Not Present

    MongoDB, the industry leader in No SQL databases, can handle a very high volume of data. In this blog, I’ll explain MongoDB create collection steps. We will also go through various other methods to create a collection in mongodb. So let’s get started.

    Mongodb create collection if not exists python

    MongoDB stores data in JSON documents in mongo collections. MongoDB collections are similar to RDBS tables.

    Before creating a collection, create the database first. Type the below command to create a database name naiveskill

    Mongodb create database

    use naiveskill
    Mongodb create collection if not exists python

    type the below command to verify the current database in which the user is:

    > db
    naiveskill

    Now it’s time to create the collection. Use mongodb createCollection command to create a collection in mongodb. The createCollection command follows the below syntax:

    db.createCollection(name, options)

    Where

    • Name: Name of the collection to be created in string format
    • Options : (optional)options about memory size and indexing.

    Now Type the below command a create a basic collection name test

    db.createCollection('test')
    Mongodb create collection if not exists python

    Verify the test collection by typing the below command

    show collections
    test

    Fantastic, Now you know how to create a basic collection in MongoDB. Next, I will be explaining to you how to create a collection in mongodb with schema.

    Mongodb create collection with schema

    Mongodb create collection if not exists python

    There are numerous ways to create a collection with schema in mongodb. Still, the simplest one is by using JSON schema validator.Json schema validated, validates the data schema before inserting the record. If the document you are inserting does not adhere to the schema defined, that record will be discarded.

    Let’s proceed further and create a collection name Inventory with three fields ‘brand’, ‘year’, and ‘model’.

    Mongodb create collection with schema and document validation

    db.createCollection('Inventory', {
      validator: {
        $jsonSchema: {
          bsonType: 'object',
          required: ['brand', 'year', 'model'],
          properties: {
            title: {
              bsonType: 'string',
              description: 'must be a string and is required'
            },
            brand: {
              bsonType: 'string',
              description: 'must be a string and is required'
            },
            Year: {
              bsonType: 'string',
              description: 'must be an string and is required'
            },
            model: {
              bsonType: 'string',
              description: 'must be an array and is required',
                  }
                }
             }
          }
    });

    If you are getting Ok in the result, it means your collection will be successfully created.

    Mongodb create collection if not exists python

    Insert Document with invalid schema in mongodb collection

    Let’s insert the document into the Inventory collection by typing the below command.

    db.Inventory.insertOne({brand:"iphone",model:"6s"})
    Mongodb create collection if not exists python

    The document has not been inserted into the inventory collection because the Inventory collection expects three fields, and we have just passed two fields.

    Insert Document with valid schema in mongodb collection

    Now let’s insert a document into the mongodb collection by specifying all the mandatory fields.

    > db.Inventory.insertOne({brand:"iphone",year:"2015",model:"6s"})
    {
    	"acknowledged" : true,
    	"insertedId" : ObjectId("6129f22afe4e5ef36181631a")
    }
    >

    As you can see from the above output, that data gets correctly inserted into the mongodb collection without any error.

    Create collection in mongodb compass

    In this session, we will learn how to insert data into mongodb collection using a mongodb compass.

    You can follow this link to download the Mongodb compass.

    Open the Mongodb compass and paste the below connection string to connect to mongodb.

    mongodb://localhost:27017/admin

    Mongodb create collection if not exists python

    Click on create a database to create a new database.

    Mongodb create collection if not exists python

    Now provide the database name and a collection name

    Mongodb create collection if not exists python

    Click on create a database to create the naive database and testnaive collection.

    Note: While creating a mongodb collection, you have the option to select a capped collection or custom collection, or time-series collection. More details about such types of collections can be found here.

    Now, Click on database naive, and it will show you all the collections under it.

    Mongodb create collection if not exists python

    Similarly, the new collection can be created by clicking on CREATE COLLECTION button.

    MongoDB create collection if not exists

    Sometimes we need to check if the collection already exists before creating a new one. You can use the below command to check if the collection already exists in mongodb before creating a new one.

    db.getCollectionNames({name: "<collectioon_name>"}, 
    	function(err, names) {console.log('Exists: ', names.length < 0)
    	});

    But this method is not recommended. The simplest way will be to use any programming language like python or node js to interact with MongoDB. You can follow this link to have a basic idea about how to interact with mongodb using python.

    In python client, you can type the below command to get a list of collections.

    import pymongo
    client = pymongo.MongoClient("mongodb://localhost:27017/")
    client['<database_name>'].list_collection_names()

    Explanation

    • First we are import the pymongo client in python shell.Please make sure you to downloaded the pymongo package before importing.
    • Then in the second step we are creating a mongo client.
    • Then finally using mongo client we are listing all collection in particular database.

    Mongodb create collection nodejs

    Mongodb has many drivers using which you can interact with Mongodb, and one of such drivers is node.js. The MongoDB Node.js driver allows Node.js applications to connect to MongoDB and work with data.

    Save the below command into a file name create_test_collection.js to create a database name naiveskill in the test database.

    // import mongodb 
    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://localhost:27017/test";
    //client connect 
    MongoClient.connect(url, function(err, db) {
      if (err) throw err;
      dbo.createCollection("naiveskill", function(err, res) {
        if (err) throw err;
        console.log("Collection created!");
        db.close();
      });
    });

    Now run the below command using node.

    node create_test_collection.js
    Collection is created!

    Awesome, You have successfully created a collection using node.js.

    Mongodb create collection python

    Python is the first choice of data scientists and data engineers for language selection. This is because of the vast community support and multiple available packages.

    And MongoDB, one of the most famous No SQL databases, can be used to build web applications, JSON APIs, etc.

    To connect MongoDB with python, we can use the pymongo driver. It is the official driver provided by MongoDB.

    Before creating a collection in mongodb, a database must be created. To create a database, a mongo client needs to be created. Once the client gets created

    import pymongo
    client = pymongo.MongoClient("mongodb://localhost:27017/")
    db = client['naiveskill']

    Now type the below command to create a collection name mycollection

    collection = db['myCollection']

    Delete a mongodb collection

    Deleting a collection in mongodb is quite simple. We can use the drop() command to delete a collection in mongodb.

    Type the below command to delete the Inventory collection that we have created earlier

    db.Inventory.drop()
    true

    Mongodb create document

    Mongodb creating documents means inserting a document in the mongodb collection. In mongodb, you have the flexibility to insert either a single document or multiple documents at once.

    Mongodb insert single documents

    With the mongodb insert command, we can insert a single document into the mongodb collection.

    Type the below command to insert a document in the tech collection

    db.tech.insert(
     {
     'Kind': 'Mobile',
     'lang': 'iphone 6s',
     'Rating': 4.2
    })
    > db.tech.insert(
    ...  {
    ...  'Kind': 'Mobile',
    ...  'brand': 'iphone 6s',
    ...  'Rating': 4.2
    ... })
    WriteResult({ "nInserted" : 1 })

    Mongodb insert multiple documents

    Similarly, using mongodb insert many commands, we can insert multiple documents into the mongodb collections.

    > db.tech.insertMany([
    ... {
    ...     'Kind': 'Mobile',
    ...     'lang': 'iphone 6s',
    ...     'Rating': 4.2
    ...  },
    ... {
    ...     'Kind': 'laptop',
    ...     'lang': 'acer',
    ...     'Rating': 3.9
    ...  },
    ...  {
    ...     'Kind': 'mobile',
    ...     'lang': 'samsung',
    ...     'Rating': 4.0
    ...  },
    ...  ])
    {
      "acknowledged" : true,
      "insertedIds" : [
        ObjectId("60c37883a9c3d411ad96c6e7"),
        ObjectId("60c37883a9c3d411ad96c6e8"),
        ObjectId("60c37883a9c3d411ad96c6e9")
      ]
    }

    You can follow this link to get the complete tutorial on mongodb commands.

    Conclusion

    Finally, we have come to an end of this basic mongodb create collection tutorial. In this tutorial, we have learned different ways to create a collection in mongodb.

    I hope you have liked this tutorial. Please do let me know in the comment box if you face any issues while following along.

    More to read

    How to create a database in mongodb

    Install MongoDB using docker

    MongoDB vs Mysql

    Mongodb vs PostgreSQL

    Does MongoDB Create collection if not exists?

    If a collection does not exist, MongoDB creates the collection when you first store data for that collection. You can also explicitly create a collection with various options, such as setting the maximum size or the documentation validation rules.

    How do you create a collection in MongoDB Python?

    To create a collection in MongoDB, use database object and specify the name of the collection you want to create. MongoDB will create the collection if it does not exist.

    Does MongoDB automatically create collections?

    MongoDB creates collections automatically when you insert some documents. For example: Insert a document named seomount into a collection named SSSIT. The operation will create the collection if the collection does not currently exist.

    How do I create a collection schema in MongoDB?

    Basically, MongoDB is schema-less database, we cannot create schema in MongoDB, but we enforce the collection documents in application code or using MongoDB atlas GUI tool. For generating schema first we need to connect to the specified database and collections in MongoDB.