How to find a document in a mongo collection based on whether a field exists or not

MongoDB find syntax is pretty simple. Lets have a collection named users and find all the documents in the collection,

// Query
db.users.find({})

// Result
;[
  {
    email: 'one@email.com',
    name: 'one',
  },
  {
    firstName: 'two',
  },
  {
    email: 'three@email.com',
    firstName: 'three',
  },
]

If we need to filter by some field then,

// Query
db.users.find({ email: 'one@email.com' })

// Result
;[
  {
    email: 'one@email.com',
    name: 'one',
  },
]

What if we need to filter all the documents based on specific field. For example,

  • list all the document which don't have email field
  • list all documents which have firstName field

Filter document which don't have email field

It can be easily achieved using $exists operator on the field.

// Query
db.users.find({ email: { $exists: false } })

// Result
;[
  {
    firstName: 'two',
  },
]

Filter document which have firstName field

// Query
db.users.find({ firstName: { $exists: true } })

// Result
;[
  {
    firstName: 'two',
  },
  {
    email: 'three@email.com',
    firstName: 'three',
  },
]

MongoDB is very powerful and it provides a lot of methods to query what you exactly want. Hope you find this tutorial helpful šŸ¤—

šŸ”„ Limited Time Offer
Coding with AI: Learn to build a SaaS MVP in 10 days

Coding with AI: Learn to build a SaaS MVP in 10 days

Master practical AI development to build and launch your startup MVP in weeks instead of months. Learn to leverage AI tools and APIs effectively.

  • šŸŽÆ Build real MVP: AI-powered SaaS from idea to launch
  • šŸ¤– Integrate ChatGPT, Claude, and other AI APIs efficiently
  • šŸ’° Implement AI features users will pay for
  • āš”ļø AI-assisted coding patterns to ship 10x faster
  • šŸš€ Launch your product in 10 days, not 10 months