Kevin O.
Kevin O.

Reputation: 79

How do I update a field in a sub-document array with a field from the document in MongoDB?

I have a large amount of data (~160M items) where a date value wasn't populated on the sub-document array fields, but was populated on the parent document. I'm very new to MongoDB and having trouble figuring out how to $set the field to match. Here's a sample of the data:

{
   "_id": "5f11d4c48663f32e940696ed",
   "Widgets":[{
         "WidgetId":663,
         "Name":"Super Widget 2.0",
         "Created":null,
         "LastUpdated":null
      }],
   "Status":3,
   "LastUpdated":null,
   "Created": "2018-11-09T18:22:16.000Z"
   }
}

My knowledge of MongoDB is pretty limited but here's the basic aggregation I have created for part of the pipeline and where I'm struggling:

db.sample.aggregate(
    [
        { 
            "$match" : { 
                "Donors.$.Created" : { 
                    "$exists" : true
                }
            }
        }, 
        { 
            "$match" : { 
                "Widgets.$.Created" : null
            }
        }, 
        { 
            "$set" : { 
                "Widgets.$.Created" : "Created"     // <- This is where I can't figure out how to define the reference to the parent "Created" field
            }
        }
    ]
);

The desired output would be:

{
   "_id": "5f11d4c48663f32e940696ed",
   "Widgets":[{
         "WidgetId":663,
         "Name":"Super Widget 2.0",
         "Created":"2018-11-09T18:22:16.000Z",
         "LastUpdated":null
      }],
   "Status":3,
   "LastUpdated":null,
   "Created": "2018-11-09T18:22:16.000Z"
   }
}

Thanks for any assitance

Upvotes: 0

Views: 879

Answers (1)

GitGitBoom
GitGitBoom

Reputation: 1912

Are you attempting to add the Created field to sub documents on query/aggregation? Or are you attempting to update/save the Created field on the subdocuments?

The $ is an update operator, to be used with updateMany or updateOne. Not aggregate. https://docs.mongodb.com/manual/reference/operator/query-array/

https://docs.mongodb.com/manual/reference/operator/update-array/

If you just want to add the parents Created field to all subdocuments on query/aggregation this is all you have to do: https://mongoplayground.net/p/yHDHULCSTIz

db.collection.aggregate([
  {
    "$addFields": {
      "Widgets.Created": "$Created"
    }
  }
])

If your attempting to save the parents Created field to all subdocuments:

db.sample.updateMany({"Widgets.Created" : null}, [{$set: {"Widgets.Created" : "$Created"}}])

Note: This matches any doc that has a subdocument with a null Created field and updates all the subdocuments.

Upvotes: 2

Related Questions