In my Meteor/javascript app, I am trying to update a specific MongoDB document via $addToSet
on a certain part of that document followed by $set
on a different part of that same document. There is no overlap between these two portions, so from what I read online it should be safe. But I can't seem to get the syntax correct. How can I carry out these two operations in one javascript command? The below works as two separate commands, and I assume it would be faster if they could be combined into just one write to Mongo.
Collection.update(
{_id: documentId},
{$addToSet:
{data:
{$each: newData}
}
}
);
Collection.update(
{_id: documentId},
{$set:
{lastTxn: lastTxn,
updatedAt: new Date()}
}
);
The DifferencesIf the value already exists in the array, $push will still append the value (resulting in duplicate values). However, $addToSet only appends the value if it doesn't already exist in the array. Therefore, if the value already exists, $addToSet won't append it (it will do nothing).
You can use the updateOne() or updateMany() methods to add, update, or remove array elements based on the specified criteria. It is recommended to use the updateMany() method to update multiple arrays in a collection.
In MongoDB, the $push operator is used to appends a specified value to an array. If the mentioned field is absent in the document to update, the $push operator add it as a new field and includes mentioned value as its element. If the updating field is not an array type field the operation failed.
The $addToSet operator adds a value to an array unless the value is already present, in which case $addToSet does nothing to that array. The $addToSet operator has the form: { $addToSet: { <field1>: <value1>, ... } } To specify a <field> in an embedded document or in an array, use dot notation.
As long as they are not on the same path ( which is the one thing you cannot do ) then it is perfectly fine. The $set
and $addToSet
operations are just top level "keys" of the "update document":
Collection.update(
{ "_id": documentId },
{
"$addToSet": { "data": { "$each": newData } },
"$set": {
"lastTxn": lastTxn,
"updatedAt": new Date()
}
}
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With