Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to find specific array elements in MongoDB document with query and filter with range?
To find specific array elements in MongoDB documents with query and filter with range, use the aggregation pipeline with $match to filter documents and $filter to filter array elements based on price range conditions.
Syntax
db.collection.aggregate([
{ $match: { field: "value" } },
{
$addFields: {
arrayField: {
$filter: {
input: "$arrayField",
cond: {
$and: [
{ $gt: ["$$this.field", minValue] },
{ $lt: ["$$this.field", maxValue] }
]
}
}
}
}
}
]);
Sample Data
db.demo351.insertMany([
{
"_id": "101",
"ProductDetails": [
{
"ProductName": "Product-1",
"ProductPrice": 500
},
{
"ProductName": "Product-2",
"ProductPrice": 400
}
]
},
{
"_id": "102",
"ProductDetails": [
{
"ProductName": "Product-3",
"ProductPrice": 200
},
{
"ProductName": "Product-4",
"ProductPrice": 800
}
]
}
]);
{
"acknowledged": true,
"insertedIds": {
"0": "101",
"1": "102"
}
}
Display All Documents
db.demo351.find();
{
"_id": "101", "ProductDetails": [
{ "ProductName": "Product-1", "ProductPrice": 500 },
{ "ProductName": "Product-2", "ProductPrice": 400 }
]
}
{
"_id": "102", "ProductDetails": [
{ "ProductName": "Product-3", "ProductPrice": 200 },
{ "ProductName": "Product-4", "ProductPrice": 800 }
]
}
Example: Filter Products by Price Range
Find products in document "102" with price between 600 and 900 ?
db.demo351.aggregate([
{
$match: { _id: "102" }
},
{
$addFields: {
ProductDetails: {
$filter: {
input: "$ProductDetails",
cond: {
$and: [
{ $gt: ["$$this.ProductPrice", 600] },
{ $lt: ["$$this.ProductPrice", 900] }
]
}
}
}
}
}
]);
{ "_id": "102", "ProductDetails": [{ "ProductName": "Product-4", "ProductPrice": 800 }] }
How It Works
-
$matchfilters documents by specific criteria (document ID "102") -
$filterprocesses the ProductDetails array -
$$this.ProductPricereferences each array element's ProductPrice field -
$andensures both price conditions are met (greater than 600 AND less than 900)
Conclusion
Use MongoDB aggregation with $match and $filter to find specific array elements within documents based on range conditions. The $filter operator processes array elements and returns only those matching the specified criteria.
Advertisements
