
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
Using Object as Key for Finding Values in MongoDB
For finding values, use find() in MongoDB. Under that, use dot notation. Let us create a collection with documents −
> db.demo361.insertOne({"details":{"FirstName":"Chris","LastName":"Brown"}}); { "acknowledged" : true, "insertedId" : ObjectId("5e56a61f54a481fef8ec7a19") } > db.demo361.insertOne({"details":{"FirstName":"David","LastName":"Miller"}}); { "acknowledged" : true, "insertedId" : ObjectId("5e56a62854a481fef8ec7a1a") } > db.demo361.insertOne({"details":{"FirstName":"John","LastName":"Doe"}}); { "acknowledged" : true, "insertedId" : ObjectId("5e56a63654a481fef8ec7a1b") }
Display all documents from a collection with the help of find() method −
> db.demo361.find();
This will produce the following output −
{ "_id" : ObjectId("5e56a61f54a481fef8ec7a19"), "details" : { "FirstName" : "Chris", "LastName" : "Brown" } } { "_id" : ObjectId("5e56a62854a481fef8ec7a1a"), "details" : { "FirstName" : "David", "LastName" : "Miller" } } { "_id" : ObjectId("5e56a63654a481fef8ec7a1b"), "details" : { "FirstName" : "John", "LastName" : "Doe" } }
Following is the query to use an object as key for finding values −
> db.demo361.find({},{"details.LastName":1});
This will produce the following output −
{ "_id" : ObjectId("5e56a61f54a481fef8ec7a19"), "details" : { "LastName" : "Brown" } } { "_id" : ObjectId("5e56a62854a481fef8ec7a1a"), "details" : { "LastName" : "Miller" } } { "_id" : ObjectId("5e56a63654a481fef8ec7a1b"), "details" : { "LastName" : "Doe" } }
Advertisements