For such conversion, use aggregate. Let us create a collection with documents −
> db.demo343.insertOne({ ... _id: 101, ... UserName: "Chris", ... details: [ ... {"Name":"John"}, ... {"Name":"David"} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : 101 }
Display all documents from a collection with the help of find() method −
> db.demo343.find().pretty();
This will produce the following output −
{ "_id" : 101, "UserName" : "Chris", "details" : [ { "Name" : "John" }, { "Name" : "David" } ] }
Following is the query to convert an array of objects into an array of embedded documents with a field containing the original array element value −
> db.demo343.aggregate([ ... { ... $addFields: { ... details: { ... $map: { ... input: "$details", ... in: { Name: "$$this" } ... } ... } ... } ... }, ... { $out: "demo343" } ... ])
Display all documents from a collection with the help of find() method −
> db.demo343.find().pretty();
This will produce the following output −
{ "_id" : 101, "UserName" : "Chris", "details" : [ { "Name" : { "Name" : "John" } }, { "Name" : { "Name" : "David" } } ] }