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
Promote subfields to top level in projection without listing all keys in MongoDB?
To promote subfields to top level in projection, use $objectToArray and $arrayToObject. Let us first create a collection with documents:
> db.promoteSubfieldsDemo.insertOne({'s':10,'y':{'t':20,'u':30,}});
{
"acknowledged" : true,
"insertedId" : ObjectId("5e038004190a577c668b55d5")
}
Following is the query to display all documents from a collection with the help of find() method −
> db.promoteSubfieldsDemo.find().pretty();
This will produce the following output −
{
"_id" : ObjectId("5e038004190a577c668b55d5"),
"s" : 10,
"y" : {
"t" : 20,
"u" : 30
}
}
Following is the query to promote subfields to top level in projection without listing all keys −
> db.promoteSubfieldsDemo.aggregate([
... { "$replaceRoot": {
... "newRoot": {
... "$arrayToObject": {
... "$concatArrays": [
... [{ "k": "s", "v": "$s" }],
... { "$objectToArray": "$y" }
... ]
... }
... }
... }}
... ]);
This will produce the following output −
{ "s" : 10, "t" : 20, "u" : 30 }Advertisements