How do you convert an array of ObjectIds into an array of embedded documents with a field containing the original array element value?


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"
         }
      }
   ]
}

Updated on: 02-Apr-2020

52 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements