Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to find specific array elements in MongoDB document with query and filter with range?
For this, use aggregate() in MongoDB. Let us create a collection with documents −
> db.demo351.insertOne(
... {
...
... "_id" : "101",
... "ProductDetails" : [
... {
... "ProductName" : "Product-1",
... "ProductPrice" :500
... },
... {
... "ProductName" : "Product-2",
... "ProductPrice" :400
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : "101" }
> db.demo351.insertOne(
... {
...
... "_id" : "102",
... "ProductDetails" : [
... {
... "ProductName" : "Product-3",
... "ProductPrice" :200
... },
... {
... "ProductName" : "Product-4",
... "ProductPrice" :800
... }
... ]
... }
... );
{ "acknowledged" : true, "insertedId" : "102" }
Display all documents from a collection with the help of find() method &mnus;
> db.demo351.find();
This will produce the following output −
{
"_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 }
]
}
Following is the query to find specific array elements in MongoDB document with query and filter with range −
> db.demo351.aggregate([
... {
... $match: { _id: "102" }
... },
... {
... $addFields: {
... ProductDetails: {
... $filter: {
... input: "$ProductDetails",
... cond: {
... $and: [
... { $gt: [ "$$this.ProductPrice", 600 ] },
... { $lt: [ "$$this.ProductPrice", 900 ] }
... ]
... }
... }
... }
... }
... }
... ])
This will produce the following output −
{ "_id" : "102", "ProductDetails" : [ { "ProductName" : "Product-4", "ProductPrice" : 800 } ] }Advertisements