I want to create a new field in an already created document. How can this be done using MongoDB query?

To create a new field in an already existing MongoDB document, use the $set operator with the update() method. The $set operator adds new fields or modifies existing field values.

Syntax

db.collection.update(
    { "matchingField": "value" },
    { $set: { "newFieldName": "newValue" } }
);

Create Sample Data

Let us first create a collection with documents ?

db.createFieldDemo.insertMany([
    { "StudentFirstName": "John", "StudentAge": 21 },
    { "StudentFirstName": "Larry", "StudentAge": 23 },
    { "StudentFirstName": "Chris", "StudentAge": 22 },
    { "StudentFirstName": "David", "StudentAge": 25 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd99e28b50a6c6dd317ad95"),
        ObjectId("5cd99e2fb50a6c6dd317ad96"),
        ObjectId("5cd99e38b50a6c6dd317ad97"),
        ObjectId("5cd99e43b50a6c6dd317ad98")
    ]
}

Display all documents to verify the data ?

db.createFieldDemo.find().pretty();
{
    "_id": ObjectId("5cd99e28b50a6c6dd317ad95"),
    "StudentFirstName": "John",
    "StudentAge": 21
}
{
    "_id": ObjectId("5cd99e2fb50a6c6dd317ad96"),
    "StudentFirstName": "Larry",
    "StudentAge": 23
}
{
    "_id": ObjectId("5cd99e38b50a6c6dd317ad97"),
    "StudentFirstName": "Chris",
    "StudentAge": 22
}
{
    "_id": ObjectId("5cd99e43b50a6c6dd317ad98"),
    "StudentFirstName": "David",
    "StudentAge": 25
}

Example: Adding a New Field

Create a new field "StudentLastName" for David's document ?

db.createFieldDemo.update(
    { _id: ObjectId("5cd99e43b50a6c6dd317ad98") },
    { $set: { "StudentLastName": "Miller" } }
);
WriteResult({ "nMatched": 1, "nUpserted": 0, "nModified": 1 })

Verify Result

Check all documents to see the newly added field ?

db.createFieldDemo.find().pretty();
{
    "_id": ObjectId("5cd99e28b50a6c6dd317ad95"),
    "StudentFirstName": "John",
    "StudentAge": 21
}
{
    "_id": ObjectId("5cd99e2fb50a6c6dd317ad96"),
    "StudentFirstName": "Larry",
    "StudentAge": 23
}
{
    "_id": ObjectId("5cd99e38b50a6c6dd317ad97"),
    "StudentFirstName": "Chris",
    "StudentAge": 22
}
{
    "_id": ObjectId("5cd99e43b50a6c6dd317ad98"),
    "StudentFirstName": "David",
    "StudentAge": 25,
    "StudentLastName": "Miller"
}

Key Points

  • $set creates new fields as simple values, unlike $addToSet which creates arrays
  • Use updateMany() to add the same field to multiple documents
  • If the field already exists, $set will update its value

Conclusion

Use the $set operator with update() to create new fields in existing MongoDB documents. This approach adds clean field-value pairs without creating unnecessary array structures.

Updated on: 2026-03-15T01:22:07+05:30

164 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements