Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update mongodb array of ObjectId to array of objects?

I want to update an array field in a document to array of object.

from:

{
 _id: ObjectId("634a84bc0c43db0c08596fda"),
 array1: [ObjectId("61542ed38929eff201f1a449"), ObjectId("61542ed38929eff201f1a450")]
}

to:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{
 _id: ObjectId("634a84bc0c43db0c08596fda"),
 array1: [
     {
      _id: ObjectId("634a84bc0c43db0c08596fd0")
      doc2: ObjectId("61542ed38929eff201f1a449")
     },
     {
      _id: ObjectId("634a84bc0c43db0c08596fd1")
      doc2: ObjectId("61542ed38929eff201f1a450")
     }
  ]
}

This is what I tried:

 db.doc1.aggregate(
  [
    { $match: 
      {       
        _id: ObjectId('634a84bc0c43db0c08596fda')
      } 
    },
    { $project:
        { 
          array1:
          {
            $map: {
                  input: "$array1",
                  as: "doc2",
                  in: { 
                      _id: new ObjectId(),
                      doc2: "$$doc2"
                  }
                }
          }
        }
    }
  ]
);

db.doc1.updateOne(
    {        
      _id: ObjectId('634a84bc0c43db0c08596fda') 
    },
    { $set:
        { 
          array1: "resultAggregate"
        }
    }
);

the result of db.doc1.aggregate:

[
  {
    "_id": {
      "$oid": "634a84bc0c43db0c08596fda"
    },
    "array1": [
      {
        "_id": {
          "$oid": "634a84bc0c43db0c08596fd0"
        },
        "doc2": {
          "$oid": "61542ed38929eff201f1a449"
        }
      },
      {
        "_id": {
          "$oid": "634a84bc0c43db0c08596fd1"
        },
        "doc2": {
          "$oid": "61542ed38929eff201f1a450"
        }
      }
    ]
  }
]

The problem:

How to passe the aggregate result to updateOne query or combine these two queries into one query?

>Solution :

It looks like what you need is to update with a pipeline:

db.collection.update({
  _id: ObjectId("634a84bc0c43db0c08596fda")
},
[
  {
    $set: {
      array1: {
        $map: {
          input: "$array1",
          as: "doc2",
          in: {
            _id: new ObjectId(),
            doc2: "$$doc2"
          }
        }
      }
    }
  }
])
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading