0

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?

1
  • Maybe you are looking for $merge Commented Oct 15, 2022 at 14:11

1 Answer 1

1

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"
          }
        }
      }
    }
  }
])
Sign up to request clarification or add additional context in comments.

1 Comment

I tried $set and then I tried to use two queries and it turn out that I was messing brackets ty.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.