How to find a document in mongo using the partial value of a field
Paramanantham Harrison
Posted on January 16, 2020
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',
},
];
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',
},
];
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 fieldname
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',
},
];
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',
},
];
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
Posted on January 16, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
January 9, 2020