DEV Community

Paramanantham Harrison
Paramanantham Harrison

Posted on • Originally published at learnwithparam.com on

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',
  },
];
Enter fullscreen mode Exit fullscreen mode

If we need to filter by some field then,

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

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

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

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

Filter document which doesn’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',
  },
];
Enter fullscreen mode Exit fullscreen mode

Filter document which have firstName field

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

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

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

Top comments (0)