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 🤗

Beginners to ProNode Js

Visual Guide to API Design Best Practices

This visual eBook covers essential best practices for designing robust APIs using REST principles.

This book is ideal for beginners and backend developers seeking to enhance their API design skills. However, it is not suited for those seeking an in-depth exploration of API design. This book is a quick read under 40 slides like scrolling through your instagram feed.

Visual Guide to API Design Best Practices