Querying Specific Elements within Object Arrays
Example 1
Let’s retrieve only the line items where the product quantity exceeds 1 for the order with order_id “12345“:
db.orders.find(
{ "order_id": "12345", "line_items": { $elemMatch: { "quantity": { $gt: 1 } } } }
)
Output:
[
{
_id: ObjectId('60c50f6852124c2e184f0625'),
order_id: '12345',
customer: 'John Doe',
line_items: [
{ product_id: 'P001', quantity: 2, price: 10 },
{ product_id: 'P002', quantity: 1, price: 20 }
]
}
]
Explanation: This MongoDB query searches for documents in the “orders” collection with an “order_id” of “12345” and at least one “line_item” with a “quantity” greater than 1.
Example 2
Now, let’s retrieve only the line items where the product quantity exceeds 1 for the order with order_id “12345”, including only the matched elements from the line_items array:
db.orders.find(
{ "order_id": "12345", "line_items": { $elemMatch: { "quantity": { $gt: 1 } } } },
{ "_id": 0, "line_items.$": 1 }
)
Output:
[
{ line_items: [ { product_id: 'P001', quantity: 2, price: 10 } ] }
]
Explanation: This MongoDB query finds documents in the “orders” collection with an “order_id” of “12345” and returns only the first matching “line_item” with a “quantity” greater than 1, excluding the “_id” field from the output.
How to Retrieve only the Queried Element in an Object Array in MongoDB Collection
In MongoDB, retrieving specific elements from an object array within a document is a common requirement, especially when dealing with complex data structures. MongoDB provides powerful query operators to filter and retrieve only the elements that match certain criteria within an array. This capability is particularly useful when we need to extract specific information from deeply nested arrays without retrieving the entire document
In this article, We will learn about How to Retrieve only the queried element in an object array in the MongoDB collection along with the examples in detail and so on.
Contact Us