In this MongoDB tutorial, we will learn to return only matching array elements in MongoDB. We will cover this topic with distinct operations and examples. The following topics that we are going to cover in this tutorial:
- MongoDB return only matching array elements query
- MongoDB return only matching array elements with condition
- MongoDB return only matching array elements using regex
- MongoDB return only matching array elements by id
- MongoDB return only matching array elements by value
- MongoDB return only matching nested array elements
- MongoDB return only matching array elements null
- MongoDB return only matching array elements using python
MongoDB return only matching array elements query
MongoDB provides the $elemMatch operator to limit the content of a <array> field from the query results to contain only the first element matching the $elemMatch condition.
Note that, Both the $ operator and the $elemMatch operator project the first matching element from the array based on a condition.
- The $ operator is used to project the first matching array element from each document in a collection based on some condition from the query statement.
- The $elemMatch projection operator is used to take an explicit condition argument.
Let’s get brief out with the help of an example.
Example:
The following documents will insert into the player collection.
db.player.insertOne( {
name: "player1",
games: [ { game: "Cricket", score: 8 }, { game: "Hockey", score: 5 } ],
joined: new Date("2021-09-01"),
lastLogin: new Date("2021-11-30")
} )
After inserting the documents into the collection, you can return the documents by using the find() method.

Now, we will apply the below query to return only matching array elements from the MongoDB collection.
In MongoDB version 4.4, the following projection returns the games field after the other existing fields contained in the projection even though in the document, the field is listed before joined and lastLogin fields:
db.player.find(
{ },
{ games: { $elemMatch: { score: { $gt: 5 } } },
joined: 1,
lastLogin: 1
}
)
Output:

Read MongoDB return specific fields
MongoDB return only matching array elements with condition
In this topic, you will learn to return only matching array elements that satisfy the conditions. You can use the $elemMatch projection to return only the first matching element. Let’s get brief out with the help of an example.
Example:
In the example, we will use the find() operation queries for all documents where the value of the ‘zipcode’ field is 63109. And, we will use the $elemMatch projection to return only the first matching element of the ‘students’ array where the school field has a value of 102.
The following documents will insert into the “schools” collection.
db.schools.insertMany([
{
_id: 1,
zipcode: "63109",
students: [
{ name: "john", school: 102, age: 10 },
{ name: "jess", school: 102, age: 11 },
{ name: "jeff", school: 108, age: 15 }
],
city: "United States of America"
},
{
_id: 2,
zipcode: "63110",
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
],
city: "United Kingdom"
},
{
_id: 3,
zipcode: "63109",
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
],
city: "Canada"
},
{
_id: 4,
zipcode: "63109",
students: [
{ name: "barney", school: 102, age: 7 },
{ name: "ruth", school: 102, age: 16 },
],
city: "New Zealand"
}
])
After inserting the documents into the collection, you can return the documents by using the find() method.

Now, we will apply the below query to MongoDB collection to return only matching array elements with conditions.
db.schools.find(
{ zipcode: "63109" },
{ students: { $elemMatch: { school: 102 } } }
)
The operation will return the following documents that have ‘zipcode’ equal to 63109 and the projects the ‘students’ array using the $elemMatch operator.
Output:

Note:
- This will return for the document where _id equals 1, the ‘students’ array contains multiple elements with the school field equal to 102. And the $elemMatch projection returns only the first matching element from the array.
- The documents with _id equal to 3 do not contain the ‘students’ fields in the result and there is no element in its ‘students’ array that matched the $elemMatch condition.
Check out, How to get id from mongodb after insert
MongoDB return only matching array elements using regex
In this topic, we will learn to return only matching array elements using the $regex (regular expression) operator. We will use the $regex operator to return only matching array elements.
Let’s get brief out with the help of an example.
Example:
The following documents were inserted into the ‘bois’ collection.
db.bios.find()
{
"_id" : 1,
"name" : {
"first" : "Kristen",
"last" : "Nygaard"
},
"birth" : ISODate("1956-01-31T05:00:00Z"),
"contribs" : [
"Python"
],
"awards" : [
{
"award" : "Award for the Advancement of Free Software",
"year" : 2001,
"by" : "Free Software Foundation"
},
{
"award" : "NLUUG Award",
"year" : 2003,
"by" : "NLUUG"
}
]
}
{
"_id" : 2,
"name" : {
"first" : "Dennis",
"last" : "Ritchie"
},
"birth" : ISODate("1941-09-09T04:00:00Z"),
"death" : ISODate("2011-10-12T04:00:00Z"),
"contribs" : [
"UNIX",
"C"
],
"awards" : [
{
"award" : "Turing Award",
"year" : 1983,
"by" : "ACM"
},
{
"award" : "National Medal of Technology",
"year" : 1998,
"by" : "United States"
},
{
"award" : "Japan Prize",
"year" : 2011,
"by" : "The Japan Prize Foundation"
}
]
}
{
"_id" : 3,
"name" : {
"first" : "Yukihiro",
"aka" : "Matz",
"last" : "Matsumoto"
},
"birth" : ISODate("1965-04-14T04:00:00Z"),
"contribs" : [
"Ruby"
],
"awards" : [
{
"award" : "Award for the Advancement of Free Software",
"year" : "2011",
"by" : "Free Software Foundation"
}
]
}
{
"_id" : 4,
"name" : {
"first" : "James",
"last" : "Gosling"
},
"birth" : ISODate("1955-05-19T04:00:00Z"),
"contribs" : [
"Java"
],
"awards" : [
{
"award" : "The Economist Innovation Award",
"year" : 2002,
"by" : "The Economist"
},
{
"award" : "Officer of the Order of Canada",
"year" : 2007,
"by" : "Canada"
}
]
}
{
"_id" : 5,
"name" : {
"first" : "Martin",
"last" : "Odersky"
},
"contribs" : [
"Scala"
]
}
Now, we will apply the below query where use the $regex operator to return the documents where the “name.last” field starts with the letter N (or is “LIKE N%”)
db.bios.find(
{ "name.last": { $regex: /^N/ } }
)
Output:

Read MongoDB date format
MongoDB return only matching array elements by id
In this topic, we will learn to return only matching array elements of MongoDB collection by their id.
In this case when we have two or more conditions and as a result, we get documents in which one element of the array matches one condition and another document only matches the other condition.
Let’s get brief out with the help of an example.
Example:
The following documents will insert into the articles collection.
db.articles.insert([
{
"_id" : 1,
"description" : "DESCRIPTION ARTICLE AB",
"article_code" : "AB",
"purchase" : [
{
"company" : 1,
"cost" : NumberDecimal("80.010000")
},
{
"company" : 2,
"cost" : NumberDecimal("85.820000")
},
{
"company" : 3,
"cost" : NumberDecimal("79.910000")
}
],
"stock" : [
{
"country" : "01",
"warehouse" : {
"code" : "02",
"units" : 10
}
},
{
"country" : "02",
"warehouse" : {
"code" : "02",
"units" : 8
}
}
]
},
{
"_id" : 2,
"description" : "DESCRIPTION ARTICLE AC",
"article_code" : "AC",
"purchase" : [
{
"company" : 1,
"cost" : NumberDecimal("90.010000")
},
{
"company" : 2,
"cost" : NumberDecimal("95.820000")
},
{
"company" : 3,
"cost" : NumberDecimal("89.910000")
}
],
"stock" : [
{
"country" : "01",
"warehouse" : {
"code" : "01",
"units" : 20
}
},
{
"country" : "02",
"warehouse" : {
"code" : "02",
"units" : 28
}
}
]
}
])
After inserting the documents, return all the documents using the find() method.

Now, we will apply the below query to return only matching array elements by id.
db.articles.find({
"_id" : 2,
"stock.country" : "01",
"stock.warehouse.code" : "02"
}).pretty();
In this code, we have defined a particular “id: 2” and accessed the matching array elements by their id.
Output:

Check out, MongoDB check if the document exists
MongoDB return only matching array elements by value
In this topic, you will learn to return only matching array elements by value from the MongoDB collection. MongoDB provides the $elemMatch operator to return only matching array elements by value. Let’s get brief out with the help of an example.
Example:
The following documents were inserted into the articles collection.
db.articles.find().pretty()
{
"_id" : 1,
"description" : "DESCRIPTION ARTICLE AB",
"article_code" : "AB",
"purchase" : [
{
"company" : 1,
"cost" : NumberDecimal("80.010000")
},
{
"company" : 2,
"cost" : NumberDecimal("85.820000")
},
{
"company" : 3,
"cost" : NumberDecimal("79.910000")
}
],
"stock" : [
{
"country" : "01",
"warehouse" : {
"code" : "02",
"units" : 10
}
},
{
"country" : "02",
"warehouse" : {
"code" : "02",
"units" : 8
}
}
]
}
{
"_id" : 2,
"description" : "DESCRIPTION ARTICLE AC",
"article_code" : "AC",
"purchase" : [
{
"company" : 1,
"cost" : NumberDecimal("90.010000")
},
{
"company" : 2,
"cost" : NumberDecimal("95.820000")
},
{
"company" : 3,
"cost" : NumberDecimal("89.910000")
}
],
"stock" : [
{
"country" : "01",
"warehouse" : {
"code" : "01",
"units" : 20
}
},
{
"country" : "02",
"warehouse" : {
"code" : "02",
"units" : 28
}
}
]
}
After that, we will apply the below query to return only matching array elements by value from the MongoDB collection.
db.articles.find(
{ stock : { $elemMatch : { country : "01", "warehouse.code" : "02" } } }
).pretty()
Here, we have used the $elemMatch operator to return only matching array elements by value.
Output:

Read How to delete documents in MongoDB
MongoDB return only matching nested array elements
In this topic, you will understand to return only matching nested array elements. You can use the $elemMatch operator to return only the matching nested array element.
Example:
The following documents will insert into the mytest collection.
db.mytest.insert({
name: "United States of America",
top: [
{x:1, y:2, nest: [{p:1, q:2}, {p:2, q:3}]},
{x:2, y:3, nest: [{p:4, q:5}, {p:6, q:7}]}
]
})
After inserting the document return the document using the find() method.

Now, we will apply the below query to the mytest collection to return only matching nested array elements.
MongoDB is having a positional $ operator which is used to return an array element at the matched index from a query condition.
db.mytest.findOne(
{
"top.nest": { $elemMatch: {p:6}}
},
{'top.nest.$': 1}
)
However, this only returns the “first” matched index of the “outer” most array element.
Output:

Check out, Select the first element in an array in MongoDB
MongoDB return only matching array null elements
In this topic, you will understand to return only matching array null elements from the MongoDB collection. You can use the $elemMatch projection to return only the first matching null element. Let’s get brief out with the help of an example.
Example:
The subsequent documents will insert into the ‘schools’ collection.
db.schools.insertMany([
{
_id: 1,
zipcode: "63109",
students: [
{ name: "john", school: null, age: 10 },
{ name: "jess", school: 102, age: 11 },
{ name: "jeff", school: 108, age: 15 }
],
city: "United States of America"
},
{
_id: 2,
zipcode: "63110",
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
],
city: "United Kingdom"
},
{
_id: 3,
zipcode: "63109",
students: [
{ name: "ajax", school: 100, age: 7 },
{ name: "achilles", school: 100, age: 8 },
],
city: "Canada"
},
{
_id: 4,
zipcode: "63109",
students: [
{ name: "barney", school: null, age: 7 },
{ name: "ruth", school: null, age: 16 },
],
city: "New Zealand"
}
])
After inserting the documents into the collection, you can return the documents by using the find() method.

Now, we will apply the below query to MongoDB collection to return only matching array null elements.
db.schools.find(
{ zipcode: "63109" },
{ students: { $elemMatch: { school: null } } }
)
The operation will return the following documents that have ‘zipcode’ equal to 63109 and the projects the ‘students’ array where the ‘school’ field is null using the $elemMatch operator.
Output:

Note:
- This will return for the document where _id equals 1, the ‘students’ array contains multiple elements with the school field equal to null. And the $elemMatch projection returns only the first matching element from the array.
- The documents with _id equal to 3 do not contain the ‘students’ fields in the result and there is no element in its ‘students’ array that matched the $elemMatch condition.
Check out, MongoDB nested query
MongoDB return only matching array elements using python
In this topic, you will learn to return only matching array elements from the MongoDB collection using python. You can use the $elemMatch operator in python to return only the matching array element.
Let’s get brief out with the help of an example.
Example:
The subsequent python code will use to return only matching array elements from the existing MongoDB collection.
- First, we have imported the pymongo library for MongoDB access in python.
- Next, we make the connection with the host.
- And, we have accessed the existing database and collection, demo and schools respectively.
- After that, we have used the $elemMatch operator to return matching array element.
- Display all the documents as per defined condition.
import pymongo
myclient = pymongo.MongoClient("mongodb://127.0.0.1:27017")
mydb = myclient['demo']
mycol = mydb["schools"]
field = mycol.find(
{ "zipcode": "63109" },
{ "students": { "$elemMatch": { "school": 102 } } }
)
for returnField in field:
print(returnField)
Output:

You may like the following MongoDB tutorials:
- MongoDB aggregate $count with examples
- MongoDB count with examples
- SocketException: Address already in use MongoDB
- MongoDB get collection size
- $in MongoDB Example
In this tutorial, you have learned about MongoDB return only matching array elements with examples. And we have also covered the following list of topics:
- MongoDB return only matching array elements query
- MongoDB return only matching array elements with condition
- MongoDB return only matching array elements using regex
- MongoDB return only matching array elements by id
- MongoDB return only matching array elements by value
- MongoDB return only matching nested array elements
- MongoDB return only matching array elements null
- MongoDB return only matching array elements using python
I am Bijay having more than 15 years of experience in the Software Industry. During this time, I have worked on MariaDB and used it in a lot of projects. Most of our readers are from the United States, Canada, United Kingdom, Australia, New Zealand, etc.
Want to learn MariaDB? Check out all the articles and tutorials that I wrote on MariaDB. Also, I am a Microsoft MVP.