Check for Existing Document in MongoDB?

MongoDBDatabaseBig Data Analytics

You can use findOne() for this. Following is the syntax −

db.yourCollectionName.findOne({yourFieldName: 'yourValue'});

Let us create a collection with documents −

> db.checkExistingDemo.insertOne({"StudentName":"John"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbdf90dac184d684e3fa265")
}
> db.checkExistingDemo.insertOne({"StudentName":"Carol"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbdf912ac184d684e3fa266")
}
> db.checkExistingDemo.insertOne({"StudentName":"Sam"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbdf916ac184d684e3fa267")
}
> db.checkExistingDemo.insertOne({"StudentName":"Mike"});
{
   "acknowledged" : true,
   "insertedId" : ObjectId("5cbdf91bac184d684e3fa268")
}

Display all documents from a collection with the help of find() method −

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

This will produce the following output −

{ "_id" : ObjectId("5cbdf90dac184d684e3fa265"), "StudentName" : "John" }
{ "_id" : ObjectId("5cbdf912ac184d684e3fa266"), "StudentName" : "Carol" }
{ "_id" : ObjectId("5cbdf916ac184d684e3fa267"), "StudentName" : "Sam" }
{ "_id" : ObjectId("5cbdf91bac184d684e3fa268"), "StudentName" : "Mike" }

Following is the query to check existing document −

> db.checkExistingDemo.findOne({StudentName: 'Carol'});

This will produce the following output −

{ "_id" : ObjectId("5cbdf912ac184d684e3fa266"), "StudentName" : "Carol" }
raja
Published on 02-May-2019 07:58:12
Advertisements