
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
Display Only the Keys from Nested MongoDB Documents
Let us create a collection with documents −
> db.demo740.insertOne({ ... "details": ... [ ... { ... Name:"Chris", ... Age:21, ... CountryName:"US" ... }, ... { ... Name:"Bob", ... Age:20, ... CountryName:"UK", ... isMarried:true ... } ... ] ... }); { "acknowledged" : true, "insertedId" : ObjectId("5ead700c57bb72a10bcf066d") }
Display all documents from a collection with the help of find() method −
> db.demo740.find();
This will produce the following output −
"_id" : ObjectId("5ead700c57bb72a10bcf066d"), "details" : [ { "Name" : "Chris", "Age" : 21, "CountryName" : "US" }, { "Name" : "Bob", "Age" : 20, "CountryName" : "UK", "isMarried" : true } ] }
Following is the query to get keys of nested MongoDB documents −
> db.demo740.aggregate([ ... { ... $project: { ... ListKeys: { ... $reduce: { ... input: "$details", ... initialValue: [], ... in: { ... $concatArrays: [ ... "$$value", ... { ... $map: { ... input: { ... $objectToArray: "$$this" ... }, ... in: "$$this.k" ... } ... } ... ] ... } ... } ... } ... } ... } ... ]).pretty()
This will produce the following output −
{ "_id" : ObjectId("5ead700c57bb72a10bcf066d"), "ListKeys" : [ "Name", "Age", "CountryName", "Name", "Age", "CountryName", "isMarried" ] }
Advertisements