|
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.
|