How to set limit to $inc in MongoDB?

To set a limit to $inc in MongoDB, use a query condition with comparison operators like $lt to only increment values that meet specific criteria. This prevents incrementing values beyond a desired threshold.

Syntax

db.collection.updateMany(
    { fieldName: { $lt: limitValue } },
    { $inc: { fieldName: incrementValue } }
);

Create Sample Data

db.limitIncrementDemo.insertMany([
    { "StudentId": 101, "StudentScore": 95 },
    { "StudentId": 102, "StudentScore": 55 },
    { "StudentId": 103, "StudentScore": 67 },
    { "StudentId": 104, "StudentScore": 56 },
    { "StudentId": 105, "StudentScore": 79 }
]);
{
    "acknowledged": true,
    "insertedIds": [
        ObjectId("5cd2ce9eb64f4b851c3a13c3"),
        ObjectId("5cd2cea0b64f4b851c3a13c4"),
        ObjectId("5cd2cea1b64f4b851c3a13c5"),
        ObjectId("5cd2cea3b64f4b851c3a13c6"),
        ObjectId("5cd2cea4b64f4b851c3a13c7")
    ]
}

View Initial Data

db.limitIncrementDemo.find();
{
    "_id": ObjectId("5cd2ce9eb64f4b851c3a13c3"),
    "StudentId": 101,
    "StudentScore": 95
}
{
    "_id": ObjectId("5cd2cea0b64f4b851c3a13c4"),
    "StudentId": 102,
    "StudentScore": 55
}
{
    "_id": ObjectId("5cd2cea1b64f4b851c3a13c5"),
    "StudentId": 103,
    "StudentScore": 67
}
{
    "_id": ObjectId("5cd2cea3b64f4b851c3a13c6"),
    "StudentId": 104,
    "StudentScore": 56
}
{
    "_id": ObjectId("5cd2cea4b64f4b851c3a13c7"),
    "StudentId": 105,
    "StudentScore": 79
}

Example: Increment Only Scores Below 75

Increment StudentScore by 10 only for students with scores less than 75 ?

db.limitIncrementDemo.updateMany(
    { StudentScore: { $lt: 75 } },
    { $inc: { StudentScore: 10 } }
);
{
    "acknowledged": true,
    "matchedCount": 3,
    "modifiedCount": 3
}

Verify Result

db.limitIncrementDemo.find();
{
    "_id": ObjectId("5cd2ce9eb64f4b851c3a13c3"),
    "StudentId": 101,
    "StudentScore": 95
}
{
    "_id": ObjectId("5cd2cea0b64f4b851c3a13c4"),
    "StudentId": 102,
    "StudentScore": 65
}
{
    "_id": ObjectId("5cd2cea1b64f4b851c3a13c5"),
    "StudentId": 103,
    "StudentScore": 77
}
{
    "_id": ObjectId("5cd2cea3b64f4b851c3a13c6"),
    "StudentId": 104,
    "StudentScore": 66
}
{
    "_id": ObjectId("5cd2cea4b64f4b851c3a13c7"),
    "StudentId": 105,
    "StudentScore": 79
}

Key Points

  • Only documents with StudentScore < 75 were incremented (students 102, 103, 104).
  • Student 101 (score 95) and student 105 (score 79) were not modified as they didn't match the condition.
  • Use updateMany() to update multiple documents that match the criteria.

Conclusion

Setting limits to $inc operations is achieved by using query conditions with comparison operators. This ensures increments only apply to documents meeting specific criteria, preventing values from exceeding desired thresholds.

Updated on: 2026-03-15T01:04:17+05:30

306 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements