How to Match Multiple Values in MongoDB
Sometimes we need to query and find documents based on matching multiple field values. For example, we may need to get all the documents where the field Name
contains the value “Alex” or “Ethen”.
In this short article, we will learn how to find a specific document based on multiple field values in MongoDB. Also, we will provide an example to make the topic easier.
the aggregate()
Method in MongoDB
To match multiple values when finding a specific document in a MongoDB collection, we will use a built-in method in MongoDB named aggregate()
. This method will use keywords like $match
and $in
.
Here the keyword $match
selects a document based on specified criteria, and the keyword $in
matches the query values inside it. Let’s see an example to make it easier.
Match Multiple Values in MongoDB
Our example below illustrates how we can match multiple values when searching for a specific document. The command for this purpose will look like the following.
db.mydata.aggregate([{ $match: { Name: { $in: ["Alex", "Ethen"] } } }])
This will take all the documents that contain the Name
, Alex
, or Ethen
from the collection mydata
.
When you execute the above command, the command will show you the resulting output like the one below.
Output:
{ _id: ObjectId("63713371117701ff3d627b58"),
Name: 'Ethen',
Email: 'ethen@gmail.com',
Year: 2019 }
{ _id: ObjectId("63713371117701ff3d627b59"),
Name: 'Alex',
Email: 'alex@gmail.com',
Year: 2020 }
Note that you have to check if you are in the right collection. To switch on a specific collection, use the command use YourCollection
; otherwise, it will provide you with an error.
Please note that the commands shown in this article are for the MongoDB database and the command needs to be run on the MongoDB console.
Aminul Is an Expert Technical Writer and Full-Stack Developer. He has hands-on working experience on numerous Developer Platforms and SAAS startups. He is highly skilled in numerous Programming languages and Frameworks. He can write professional technical articles like Reviews, Programming, Documentation, SOP, User manual, Whitepaper, etc.
LinkedIn