
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to 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" ] ] }
- Related Questions & Answers
- MongoDB query to get only distinct values
- Get substring in MongoDB aggregate
- Aggregate multiple arrays into one huge array with MongoDB?
- Get the average of marks in MongoDB with aggregate?
- How to calculate sum in MongoDB with aggregate()?
- How to aggregate sum in MongoDB to get the total count?
- MongoDB aggregate to get the count of field values of corresponding duplicate names?
- Use MongoDB Aggregate and select only top record (descending)
- To Aggregate Totals in One Group with MongoDB
- Get only the FALSE value with MongoDB query
- How to aggregate array documents in MongoDB?
- How to update after aggregate in MongoDB?
- How to use MongoDB Aggregate to sort?
- MongoDB aggregate $slice to get the length of the array
- How to return only unique values (no duplicates) in MongoDB?
Advertisements