vibhor1997a
vibhor1997a

Reputation: 2376

How to add a field to array of subdocuments in all the documents in mongodb?

I have collection like below:-

{
   _id: 123,
   images: [{
     _id: ObjectId("213"),
     id: "1"
   }]
}

I want to add a field imageResourceID that is dependent on the id field.

{
   _id: 123,
   images: [{
     _id: ObjectId("213"),
     id: "1",
     imageResourceID: "1"
   }]
}

What I tried?

db.collection.aggregate([
  { "$addFields": {
    "images.imageResourceID": {
        "$map": {
        "input": "$otherImages",
        "as": "image",
        "in": "$$image.id"
      }
    }
  }}
])

It adds imageResourceID field as an array containing id fields of all of the sub documents. How can I make it to add imageResourceID field having value equal to the id field?

Thanks in advance. I am new to MongoDB so please bear with me.

Upvotes: 1

Views: 794

Answers (1)

Ashh
Ashh

Reputation: 46441

You need to loop over the images field using $map and need to specify each field inside the in expression of $map aggregation and at last use $out aggregation to write them into another collection.

db.collection.aggregate([
  { "$addFields": {
    "images": {
      "$map": {
        "input": "$images",
        "as": "image",
        "in": {
          "_id": "$$image._id"
          "id": "$$image.id",
          "imageResourceID": "$$image.id"
        }
      }
    }
  }},
  { "$out": "<output-collection>" }
])

Upvotes: 2

Related Questions