Uploaded image for project: 'Core Server'
  1. Core Server
  2. SERVER-11345

Allow update to compute expressions using referenced fields like Aggregation Framework's $project

    • Type: Icon: Improvement Improvement
    • Resolution: Done
    • Priority: Icon: Major - P3 Major - P3
    • None
    • Affects Version/s: None
    • Component/s: Write Ops
    • None
    • Query

      AF's $project allows us to compose arbitrary expressions using referenced fields from the document and primitive arithmetic operators.

      In contrast, update() only allows us to $inc a field or $set it, but not e.g. to multiply it by a constant (I see this was added in 2.6) or by another field.

      As an example, suppose I want to update a document containing the average rating of a product and the number of ratings it got.

      I want to be able to add a new rating in an atomic update by writing something like:

      db.products.update({ _id: 7 }, {
        $mul: { averageRating: '$ratingCount' },
        $add: { averageRating: 5 },
        $inc: { ratingCount: 1 },
        $div: { averageRating: '$ratingCount' }

      Alternatively I'd like to be able to run a user-provided JS function as part of the update, like the $where operator for queries, except this function can update the document.

            backlog-server-query Backlog - Query Team (Inactive)
            avish Avishay Lavie
            29 Vote for this issue
            26 Start watching this issue