- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- 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 query documents by a condition on the subdocument in MongoDB?
Let us first create a collection with documents −
> db.demo394.insertOne( ... { ... ... details: [ ... { ... _id: '1', ... startDate: '2018-01-11T07:00:00.000Z', ... endDate: '2019-01-12T07:59:59.999Z' ... }, ... { ... _id: '2', ... startDate: '2019-01-21T07:00:00.000Z', ... endDate: '2020-01-04T07:59:59.999Z' ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5e716817aa3ef9ab8ab202") }
Display all documents from a collection with the help of find() method −
> db.demo394.find();
This will produce the following output −
{ "_id" : ObjectId("5e5e716817aa3ef9ab8ab202"), "details" : [ { "_id" : "1", "startDate" : "2018-01-11T07:00:00.000Z", "endDate" : "2019-01-12T07:59:59.999Z" }, { "_id" : "2", "startDate" : "2019-01-21T07:00:00.000Z", "endDate" : "2020-01-04T07:59:59.999Z" } ] }
Following is how to query documents by a condition on the subdocument −
> db.demo394.find({ ... $expr: { ... $let: { ... vars: { "d": { $arrayElemAt: [ "$details", -1 ] } }, ... in: { $eq: [ "$$d.endDate", "2020-01-04T07:59:59.999Z" ] } ... } ... } ... })
This will produce the following output −
{ "_id" : ObjectId("5e5e716817aa3ef9ab8ab202"), "details" : [ { "_id" : "1", "startDate" : "2018-01-11T07:00:00.000Z", "endDate" : "2019-01-12T07:59:59.999Z" }, { "_id" : "2", "startDate" : "2019-01-21T07:00:00.000Z", "endDate" : "2020-01-04T07:59:59.999Z" } ] }
- Related Articles
- Query MongoDB subdocument to print on one line?
- MongoDB query to match each element in a documents array to a condition?
- Fetch multiple documents in MongoDB query with OR condition?
- MongoDB query to match documents whose _id is in an array as part of a subdocument?
- How to sort, select and query subdocument in MongoDB?
- How to fire find query on sub-documents in MongoDB?
- MongoDB query to remove subdocument from document?
- MongoDB query on nth element (variable index) of subdocument array
- MongoDB query condition on comparing 2 fields?
- Sort by subdocument in MongoDB
- MongoDB to sort by subdocument match?
- MongoDB query to skip documents
- MongoDB query to find and return subdocument with criteria?
- MongoDB - Query embedded documents?
- How to select a specific subdocument in MongoDB?

Advertisements