
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
Retrieve Array Values from a Find Query in MongoDB
To retrieve array values, use dot(.) notation. Let us first create a collection with documents −
> db.retrievingArrayDemo.insertOne( { "UserDetails" : [ { "UserName" : "John", "UserAge" : 23 } ], "UserCountryName" : "AUS", "UserLoginDate" : new ISODate(), "UserMessage" : "Hello" } ); { "acknowledged" : true, "insertedId" : ObjectId("5ce9718478f00858fb12e920") } > db.retrievingArrayDemo.insertOne( { "UserDetails" : [ { "UserName" : "Sam", "UserAge" : 24 } ], "UserCountryName" : "UK", "UserLoginDate" : new ISODate(), "UserMessage" : "Bye" } ); { "acknowledged" : true, "insertedId" : ObjectId("5ce9718478f00858fb12e921") }
Following is the query to display all documents from a collection with the help of find() method −
> db.retrievingArrayDemo.find().pretty();
This will produce the following output −
{ "_id" : ObjectId("5ce9718478f00858fb12e920"), "UserDetails" : [ { "UserName" : "John", "UserAge" : 23 } ], "UserCountryName" : "AUS", "UserLoginDate" : ISODate("2019-05-25T16:47:00.211Z"), "UserMessage" : "Hello" } { "_id" : ObjectId("5ce9718478f00858fb12e921"), "UserDetails" : [ { "UserName" : "Sam", "UserAge" : 24 } ], "UserCountryName" : "UK", "UserLoginDate" : ISODate("2019-05-25T16:47:00.670Z"), "UserMessage" : "Bye" }
Following is the query to retrieve array values from a find query −
> db.retrievingArrayDemo.find({"UserCountryName" : "UK", "UserDetails.UserName":"Sam"}).pretty();
This will produce the following output −
{ "_id" : ObjectId("5ce9718478f00858fb12e921"), "UserDetails" : [ { "UserName" : "Sam", "UserAge" : 24 } ], "UserCountryName" : "UK", "UserLoginDate" : ISODate("2019-05-25T16:47:00.670Z"), "UserMessage" : "Bye" }
Advertisements