Update multiple documents with aggregated values in MongoDB
<h2>Problem 1</h2>

<p>I have a collection named <code>recipe</code> in which all docs have a array field <code>ingredients</code>. I want to count those array items and write them into a new field <code>ingredient_count</code>.</p>

<h2>Problem 2</h2>

<p>There is also a collection named <code>ingredient</code>. The docs have a <code>count</code> field which is the total number of uses in all recipes.</p>

<h2>My Current Approach</h2>

<p>My solution right now is a script that aggregates over the collection and updates all documents one by one:</p>

<pre><code>// PROBLEM 1: update recipe documents
db.recipe.aggregate(
    [
        {
            $project: {
                numberOfIngredients: { $size: "$ingredients" }
            }
        }
    ]
).forEach(function(recipe) {
    db.recipe.updateOne(
        { _id: recipe._id },
        { $set: { incredient_count: recipe.numberOfIngredients } }
    )
});

// PROBLEM 2: update ingredient documents
db.ingredient.find().snapshot().forEach(function(ingredient) {
    db.ingredient.updateOne(
        { _id: ingredient._id },
        { $set: { count: db.recipe.count({ ingredients: { $in: [ingredient.name] } })) } }
    )
});
</code></pre>

<p>This is <strong>terribly slow</strong>. Any idea how to do this more efficiently?</p>