Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MongoDB $addtoSet and $set in the same operation

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()}
  }
);
like image 885
Jon Cursi Avatar asked Jan 24 '15 03:01

Jon Cursi


People also ask

What is difference between addToSet and push in MongoDB?

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).

How do you update an array element in MongoDB?

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.

How do I push an array object in MongoDB?

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.

How do you use $addToSet?

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.


1 Answers

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()
    }
  }
);
like image 150
Neil Lunn Avatar answered Sep 28 '22 02:09

Neil Lunn