Insert records in MongoDB collection if it does not exist?

MongoDBDatabaseBig Data Analytics

You can use update() function to insert records in MongoDB if it does not exist. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −

> db.insertIfNotExistsDemo.insertOne({"StudentName":"Mike","StudentAge":21});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7eec7b559dd2396bcfbfc2")
}
> db.insertIfNotExistsDemo.insertOne({"StudentName":"Sam","StudentAge":22});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5c7eec97559dd2396bcfbfc3")
}

Display all documents from a collection with the help of find() method. The query is as follows −

> db.insertIfNotExistsDemo.find().pretty();
The following is the output:
{
   "_id" : ObjectId("5c7eec7b559dd2396bcfbfc2"),
   "StudentName" : "Mike",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5c7eec97559dd2396bcfbfc3"),
   "StudentName" : "Sam",
   "StudentAge" : 22
}

Here is the query to insert a record if it does not already exist −

> key = {"StudentName":"David"}
{ "StudentName" : "David" }
> value = {"StudentName":"David","StudentAge":26}
{ "StudentName" : "David", "StudentAge" : 26 }
> db.insertIfNotExistsDemo.update(key, value, upsert=true);

The following is the output −

WriteResult({
   "nMatched" : 0,
   "nUpserted" : 1,
   "nModified" : 0,
   "_id" : ObjectId("5c7eecd4c743760e97af8261")
})

Let us check all documents from a collection. The query is as follows −

> db.insertIfNotExistsDemo.find().pretty();

The following is the output −

{
   "_id" : ObjectId("5c7eec7b559dd2396bcfbfc2"),
   "StudentName" : "Mike",
   "StudentAge" : 21
}
{
   "_id" : ObjectId("5c7eec97559dd2396bcfbfc3"),
   "StudentName" : "Sam",
   "StudentAge" : 22
}
{
   "_id" : ObjectId("5c7eecd4c743760e97af8261"),
   "StudentName" : "David",
   "StudentAge" : 26
}

Look at the sample output, the “StudentName”:”David” and “StudentAge”:26 has been inserted successfully.

raja
Published on 28-Mar-2019 16:58:28
Advertisements