MongoDB: Using reference as key and manually adding a value?

To manually add a value to an array in MongoDB using a reference as a key, use the $push operator. This allows you to add new elements to existing arrays, including complex objects with multiple fields.

Syntax

db.collection.update(
    { "field": "matchValue" },
    { "$push": { "arrayField": newValue } }
);

Sample Data

db.demo585.insertMany([
    {
        firstName: "John",
        lastName: "Doe",
        SubjectName: "MongoDB",
        Marks: [59]
    },
    {
        firstName: "Chris",
        lastName: "Brown",
        SubjectName: "MySQL",
        Marks: [79]
    }
]);
WriteResult({ "nInserted" : 2 })

Display all documents from the collection ?

db.demo585.find();
{ "_id" : ObjectId("5e91fd80fd2d90c177b5bcc3"), "firstName" : "John", "lastName" : "Doe", "SubjectName" : "MongoDB", "Marks" : [ 59 ] }
{ "_id" : ObjectId("5e91fd81fd2d90c177b5bcc4"), "firstName" : "Chris", "lastName" : "Brown", "SubjectName" : "MySQL", "Marks" : [ 79 ] }

Example: Adding Object to Array Using Reference

Add a complex object to John's Marks array using multiple fields as reference ?

db.demo585.update(
    {
        firstName: "John",
        lastName: "Doe",
        SubjectName: "MongoDB",
        Marks: [59]
    },
    {
        "$push": {
            "Marks": {
                "Value": 59,
                "Times": 3
            }
        }
    }
);
WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })

Verify Result

db.demo585.find();
{ "_id" : ObjectId("5e91fd80fd2d90c177b5bcc3"), "firstName" : "John", "lastName" : "Doe", "SubjectName" : "MongoDB", "Marks" : [ 59, { "Value" : 59, "Times" : 3 } ] }
{ "_id" : ObjectId("5e91fd81fd2d90c177b5bcc4"), "firstName" : "Chris", "lastName" : "Brown", "SubjectName" : "MySQL", "Marks" : [ 79 ] }

Key Points

  • Use multiple fields in the query to create a precise reference for targeting specific documents.
  • $push adds new elements to arrays without replacing existing ones.
  • You can push both simple values and complex objects with nested fields.

Conclusion

The $push operator with multiple reference fields allows precise document targeting for array updates. This approach is useful when you need to add structured data to existing arrays based on specific document characteristics.

Updated on: 2026-03-15T03:45:28+05:30

399 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements