
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
Get Only Values in Arrays with MongoDB Aggregate
Let us create a collection with documents −
> db.demo411.insertOne( ... { ... "Information" : [ ... { ... "Name1" : "Chris", ... "Name2" : "David" ... }, ... { ... "Name1" : "John", ... "Name2" : "John" ... } ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e70f19715dc524f70227682") }
Display all documents from a collection with the help of find() method −
> db.demo411.find();
This will produce the following output −
{ "_id" : ObjectId("5e70f19715dc524f70227682"), "Information" : [ { "Name1" : "Chris", "Name2" : "David" }, { "Name1" : "John", "Name2" : "John" } ] }
Following is the query to get only values in arrays −
> db.demo411.aggregate( ... [ ... {$project : { ... _id : 0, ... Information : {$map : {input : "$Information", as : "out", in : ["$$out.Name1", "$$out.Name2"]}} ... } ... } ... ] ... )
This will produce the following output −
{ "Information" : [ [ "Chris", "David" ], [ "John", "John" ] ] }
Advertisements