Create collection if not exists mongodb nodejs


Creating a Database

To create a database in MongoDB, start by creating a MongoClient object, then specify a connection URL with the correct ip address and the name of the database you want to create.

MongoDB will create the database if it does not exist, and make a connection to it.

Example

Create a database called "mydb":

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydb";

MongoClient.connect(url, function(err, db) {
  if (err) throw err;
  console.log("Database created!");
  db.close();
});

Run example »

Save the code above in a file called "demo_create_mongo_db.js" and run the file:

Run "demo_create_mongo_db.js"

C:\Users\Your Name>node demo_create_mongo_db.js

Which will give you this result:

Important: In MongoDB, a database is not created until it gets content!

MongoDB waits until you have created a collection (table), with at least one document (record) before it actually creates the database (and collection).




You can use the following syntax to insert a document into a collection in MongoDB only if it doesn’t already exist:

db.teams.update(
	{
	  team : 'Hornets'
	}, 
	 {
	  $setOnInsert: {team: 'Hornets', points: '58', rebounds: '20'}
	 },
	 {upsert: true}
)

This particular code checks if the field “team” has a value of “Hornets.” If this value exists, then nothing will happen.

However, if this value does not exist then it will insert a document with specific values for the “team”, “points”, and “rebounds” fields.

The following example shows how to use this syntax in practice.

Example: Insert if Not Exists in MongoDB

Suppose we have a collection called teams with the following documents:

db.teams.insertOne({team: "Mavs", points: 30, rebounds: 8})
db.teams.insertOne({team: "Spurs", points: 35, rebounds: 12})
db.teams.insertOne({team: "Rockets", points: 20, rebounds: 7})
db.teams.insertOne({team: "Warriors", points: 25, rebounds: 5})
db.teams.insertOne({team: "Cavs", points: 23, rebounds: 9})

Suppose we use the following code to attempt to insert a document for the team “Mavs”:

db.teams.update(
	{
	  team : 'Mavs'
	}, 
	 {
	  $setOnInsert: {team: 'Mavs', points: '58', rebounds: '20'}
	 },
	 {upsert: true}
)

Since the field “team” already contains information for the “Mavs”, none of the documents will be modified.

However, suppose we use the following code to insert a document for the team “Hornets”:

db.teams.update(
	{
	  team : 'Hornets'
	}, 
	 {
	  $setOnInsert: {team: 'Hornets', points: '58', rebounds: '20'}
	 },
	 {upsert: true}
)

Since the field “team” does not already contain information for the “Hornets”, a new document will be added to the collection with the values that we specified for each field.

Here’s what the updated collection looks like:

{ _id: ObjectId("6203df361e95a9885e1e764a"),
  team: 'Mavs',
  points: 30,
  rebounds: 8 }
{ _id: ObjectId("6203df361e95a9885e1e764b"),
  team: 'Spurs',
  points: 35,
  rebounds: 12 }
{ _id: ObjectId("6203df361e95a9885e1e764c"),
  team: 'Rockets',
  points: 20,
  rebounds: 7 }
{ _id: ObjectId("6203df361e95a9885e1e764d"),
  team: 'Warriors',
  points: 25,
  rebounds: 5 }
{ _id: ObjectId("6203df361e95a9885e1e764e"),
  team: 'Cavs',
  points: 23,
  rebounds: 9 }
{ _id: ObjectId("6203e17de42bfba74fc73325"),
  team: 'Hornets',
  points: '58',
  rebounds: '20' }

Notice that a new document has been added for the “Hornets” team.

Note: You can find the complete documentation for the $upsert function here.

Additional Resources

The following tutorials explain how to perform other common operations in MongoDB:

MongoDB: How to Add a New Field
MongoDB: How to Remove a Field
MongoDB: How to Count Distinct Values in Field

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.

Create collection if not exists mongodb nodejs

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
Create collection if not exists mongodb nodejs

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')
Create collection if not exists mongodb nodejs

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

Create collection if not exists mongodb nodejs

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.

Create collection if not exists mongodb nodejs

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"})
Create collection if not exists mongodb nodejs

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

Create collection if not exists mongodb nodejs

Click on create a database to create a new database.

Create collection if not exists mongodb nodejs

Now provide the database name and a collection name

Create collection if not exists mongodb nodejs

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.

Create collection if not exists mongodb nodejs

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

How do I create a specific collection in MongoDB?

Find() Method. In MongoDB, find() method is used to select documents in a collection and return a cursor to the selected documents. Cursor means a pointer that points to a document, when we use find() method it returns a pointer on the selected documents and returns one by one.

How do you check if collection is already exists in MongoDB?

The collectionExists method can be used to check whether a collection is present or not: MongoClient mongoClient = new MongoClient("localhost", 27017); DB db = mongoClient. getDB("baeldung"); String testCollectionName = "student"; System. out.

Does MongoDB automatically create Collection if not exists?

Create a Collection If a collection does not exist, MongoDB creates the collection when you first store data for that collection.

How do you create a collection in node JS and MongoDB?

Steps to Create Collection in MongoDB via Node..
Step 1: Start MongoDB Service. ... .
Step 2: Get the base URL to MongoDB Service. ... .
Step 3: Prepare the complete URL. ... .
Step 4: Create a MongoClient. ... .
Step 5: Make connection from MongoClient to the MongoDB Server with the help of URL..