'mongodb what is the different $setOnInsert and $set | update and insert data

I understood we need to use $setOnInsert

If an update operation with upsert: true results in an insert of a document, then $setOnInsert assigns the specified values to the fields in the document. If the update operation does not result in an insert, $setOnInsert does nothing.

mongo doc $setOnInsert

Also there is a similar question, but I still don't get it...

My question is when I want to update and insert documents and both inserting and updating documents need to modify title value, how the code will look like?

  modifyQuestion(question) {
    check(question, Object);
    Measures.update(
      {_id: question._id},
      {
        $set: {
          title: question.text,
          type: 'multipleChoice',
        },
        $setOnInsert: {
          title: question.text,
          type: 'multipleChoice',
        },
      },
      {upsert: true},
    );
  }

It might not look like a exact mongodb syntax since I'm using meteor

but I thought when document update

        $set: {
          title: question.text,
          type: 'multipleChoice',
        },

this run and when I insert another document

        $setOnInsert: {
          title: question.text,
          type: 'multipleChoice',
        },

this work?

I saw an error saying Updating the path 'title' would create a conflict at 'title' on my terminal.

Just can't add title field both in $set and $setOnInsert ?

If I just use one of $set, I could update document but not insert. Is there any way that I could insert and update document? Thank you.

From another stack overflow comment...

For example, I need a field to be true if the document was just inserted, and to be false if it was just updated. If same field exists in both $set(as false) and $setOnInsert(as true), and the document is inserted, the field in $setOnInsert should take precedence even though it exists as well in the $set section.

yes this is exactly what I know how to solve!



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source