How to properly use 'exist' function in MongoDB like in SQL?

To check for existence of a record in MongoDB (similar to SQL's EXISTS function), use findOne() method. This returns the first matching document if it exists, or null if no document matches the query criteria.

Syntax

db.collection.findOne({ field: "value" })

Sample Data

db.existsAlternateDemo.insertMany([
    { "StudentName": "Chris" },
    { "StudentName": "Chris", "StudentAge": 21 },
    { "StudentName": "Chris", "StudentAge": 22, "StudentCountryName": "US" }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5e06d23f9e4dae213890ac5c"),
        ObjectId("5e06d2559e4dae213890ac5d"),
        ObjectId("5e06d2689e4dae213890ac5e")
    ]
}

Display all documents to verify the data ?

db.existsAlternateDemo.find()
{ "_id": ObjectId("5e06d23f9e4dae213890ac5c"), "StudentName": "Chris" }
{ "_id": ObjectId("5e06d2559e4dae213890ac5d"), "StudentName": "Chris", "StudentAge": 21 }
{ "_id": ObjectId("5e06d2689e4dae213890ac5e"), "StudentName": "Chris", "StudentAge": 22, "StudentCountryName": "US" }

Example: Check if Record Exists

Check if a student from the US exists using findOne() ?

db.existsAlternateDemo.findOne({ "StudentCountryName": "US" })
{
    "_id": ObjectId("5e06d2689e4dae213890ac5e"),
    "StudentName": "Chris",
    "StudentAge": 22,
    "StudentCountryName": "US"
}

Alternative Methods

For boolean existence check without returning the document ?

db.existsAlternateDemo.countDocuments({ "StudentCountryName": "US" }) > 0
true

Key Points

  • findOne() returns the first matching document or null if none exists
  • More efficient than find() for existence checks as it stops after finding one match
  • countDocuments() can be used for pure boolean existence checks

Conclusion

Use findOne() as MongoDB's equivalent to SQL's EXISTS function. It efficiently checks for document existence and returns the matching document or null.

Updated on: 2026-03-15T01:48:43+05:30

196 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements