Update Documents

  1. Update a Single Document

    • The following example uses the db.collection.updateOne() method on the student collection to update the document where _id equals 5:
      
         db.student.updateOne(
            { _id: 5 },
            {
              $set: { name: "刘丽丽", "score.history": 90 },
              $currentDate: { lastupdated: true }
            }
         )
                                  
      • uses the $set operator to update the value of the name field to "刘丽丽" and the value of the score.history field to 90,
      • uses the $currentDate operator to update the value of the lastModified field to the current date. If lastModified field does not exist, $currentDate will create the field.
  2. Replace a Document

    • To replace the entire content of a document except for the _id field, pass an entirely new document as the second argument to db.collection.replaceOne(). The replacement document can have different fields from the original document. In the replacement document, you can omit the _id field since the _id field is immutable. However, if you do include the _id field, it must have the same value as the current value.
      
         db.student.replaceOne(
           { _id: 2 },
           { nickname: "star", phone: 19150036110 }
         )
                                  
  3. Delete Only One Document that Matches a Condition

    • To delete at most a single document that matches a specified filter (even though multiple documents may match the specified filter) use the Collection.deleteOne() method.
      
        db.student.deleteOne({_id :1  });