Home > Mobile >  How to update mongodb array of ObjectId to array of objects?
How to update mongodb array of ObjectId to array of objects?

Time:10-16

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

from:

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

to:

{
 _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?

CodePudding user response:

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"
          }
        }
      }
    }
  }
])
  • Related