

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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 query a document in MongoDB comparing fields from an array?
To compare fields from an array, use $gt and $lt. Let us create a collection with documents −
> db.demo147.insertOne({"Details":[{"Score":45},{"Score":46}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e32fa21fdf09dd6d08539be") } > db.demo147.insertOne({"Details":[{"Score":65},{"Score":86}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e32fa40fdf09dd6d08539bf") }
Display all documents from a collection with the help of find() method −
> db.demo147.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5e32fa21fdf09dd6d08539be"), "Details" : [ { "Score" : 45 }, { "Score" : 46 } ] } { "_id" : ObjectId("5e32fa40fdf09dd6d08539bf"), "Details" : [ { "Score" : 65 }, { "Score" : 86 } ] }
Here is how to query a document in MongoDB comparing fields from an array −
> db.demo147.find({ 'Details.Score': { $gt: 45, $lt: 50 }});
This will produce the following output −
{ "_id" : ObjectId("5e32fa21fdf09dd6d08539be"), "Details" : [ { "Score" : 45 }, { "Score" : 46 } ] }
- Related Questions & Answers
- How to project specific fields from a document inside an array in Mongodb?
- MongoDB query condition on comparing 2 fields?
- MongoDB query to return specific fields from an array?
- MongoDB query for fields in embedded document?
- MongoDB query to remove array elements from a document?
- MongoDB query with fields in the same document?
- MongoDB query to push document into an array
- MongoDB query for exact match on multiple document fields
- MongoDB query to remove subdocument from document?
- MongoDB - how can I access fields in a document?
- MongoDB query to update a specific document from a collection
- MongoDB query to pull a specific value from a document
- How to remove an element from a doubly-nested array in a MongoDB document?
- How do I remove a string from an array in a MongoDB document?
- MongoDB query to add new array element in document
Advertisements