
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
Query 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 } ] }
Advertisements