0

I am trying to update items in an array with unique ObjectIds (meaning add an object ID to array object that are missing them)

If I have an array of shirt objects in my collection and I try this:

db.people.update({        
    $and : [
        _id: ObjectId('5eeb44c6a042791d28a8641f'),
        {
            $or: [
            { 'shirts._id': { $eq:null } },
            { 'shirts._id':{ $exists:false } }
            ]
        }           
    ]
},{ 
    $set: { 'shirts.$[]._id': new ObjectId() }
},{
    "multi" : true
}

);

It generates IDENTICAL ObjectsIDs for each array element, I would put an unique index on this however, the use case probably wont see more then 2-3 items in the array with edge cases hitting 5-6, which seems like an abuse of an index

How can I update multiple records or multiple array objects with a unique ObjectId?

j-p
  • 3,698
  • 9
  • 50
  • 93

1 Answers1

0

When you use $set you're telling mongo to set that value to all matching elements. If the elements in the array are already defined as schemas, mongo will issue new ObjectIds for each one of them automatically.

Alternatively, you can use forEach and iterate over each matching element creating a new ObjectId.

rlecaro2
  • 755
  • 7
  • 14