DEV Community

Paramanantham Harrison
Paramanantham Harrison

Posted on • Originally published at learnwithparam.com on

How to find a document in mongo using the partial value of a field

I have my new FREE workshop on API design for beginners using Node Js and MongoDB. It is my first workshop, let's learn together. You can register for the workshop here

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 for like and comment',
  },
  {
    name: 'Two for Comments',
  },
  {
    email: 'three@email.com',
    name: 'Three for Like',
  },
];
Enter fullscreen mode Exit fullscreen mode

If we need to filter by some field then,

// Query
db.users.find({ name: 'One for like and comment' });

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

What if we need to filter by the field but we don’t know the exact case or exact value. Let’s see the example

  • list all the document which has a word like in the field name

Filter document using regular expression

It can be easily achieved using regular expression instead of string value,

// Query
db.users.find({ name: /like/ });

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

Here /like/ is the regex which will find all the word which match like. But this query is case sensitive. It won’t match Like. But its very easy to write case insensitive query,

db.users.find({ name: /like/i });

// Result
[
  {
    email: 'one@email.com',
    name: 'One for like and comment',
  },
  {
    email: 'three@email.com',
    name: 'Three for Like',
  },
];
Enter fullscreen mode Exit fullscreen mode

Adding i at the end of regex denotes match the word irrespective of the case. (uppercase, lowercase, etc).

We can use any regex-based search to filter the values in MongoDB. We will learn more regex and MongoDB tricks soon.

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

Follow me on twitter. I share my reading list and short tips on twitter

Top comments (2)

Collapse
 
energeticpixels profile image
Anthony Jackman

I am very glad I stumbled upon this post. Awesome timing. I never dawned on me that I could use REGEX as a delimited in a find request. Mind blown, going back and modifying my scripts to a KISS type of thinking. Thank you.

Collapse
 
djnitehawk profile image
Dĵ ΝιΓΞΗΛψΚ

partial matching like this with regex will not use a text index so performance will be bad on large collections. prefixed regexes will use the index afaik. so you might wanna mention that in the article. thanks for posting!