- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Find when the keys are unknown in MongoDB?
To find when the keys are unknown, use $addField and $objectToArray. Let us first create a collection with documents −
> db.demo375.insertOne( ... { ... "details":{ ... "Name":"John", ... "Age":23 ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5a0ae42ae06a1609a00b06") } > db.demo375.insertOne( ... { ... "details":{ ... "Name":"David", ... "Age":21 ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5a0ae42ae06a1609a00b07") } > db.demo375.insertOne( ... { ... "details":{ ... "Name":"David", ... "Age":22 ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e5a0ae42ae06a1609a00b08") }
Display all documents from a collection with the help of find() method −
> db.demo375.find();
This will produce the following output −
{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b06"), "details" : { "Name" : "John", "Age" : 23 } } { "_id" : ObjectId("5e5a0ae42ae06a1609a00b07"), "details" : { "Name" : "David", "Age" : 21 } } { "_id" : ObjectId("5e5a0ae42ae06a1609a00b08"), "details" : { "Name" : "David", "Age" : 22 } }
Following is the query to find when the keys are unknown −
> db.demo375.aggregate([ ... { "$addFields": { ... "UnknownKeys": { "$objectToArray": "$$ROOT" } ... }}, ... { "$match": { "UnknownKeys.v.Name": "David" }}, ... { "$project": { "UnknownKeys": 0 }} ... ])
This will produce the following output −
{ "_id" : ObjectId("5e5a0ae42ae06a1609a00b07"), "details" : { "Name" : "David", "Age" : 21 } } { "_id" : ObjectId("5e5a0ae42ae06a1609a00b08"), "details" : { "Name" : "David", "Age" : 22 } }
Advertisements