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
A collection in MongoDB is the same as a table in MySQL
Creating a Collection
To create a collection in MongoDB, use the createCollection() method:
Example
Create a collection called "customers":
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mydb");
dbo.createCollection("customers", function(err, res) {
if (err) throw err;
console.log("Collection created!");
db.close();
});
});
Run example »
Save the code above in a file called "demo_mongodb_createcollection.js" and run the file:
Run "demo_mongodb_createcollection.js"
C:\Users\Your Name>node demo_mongodb_createcollection.js
Which will give you this result:
Important: In MongoDB, a collection is not created until it gets content!
MongoDB waits until you have inserted a document before it actually creates the collection.
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).