Question

I have a collection of documents for the form:

{ name:String, groceries:{ apples:Number, cherries:Number, prunes:Number } }

Now, every query I have to increment with positive and/or negative values for each element in "groceries". It is not important what keys or how many, I just added some examples.

I could do a :

var dataToBeIncremented = stuff;
var $inc = {};
for each( var index in dataToBeIncremented )
{
    $inc[ "groceries." + index ] = dataToBeIncremented[ index ];
}

then

db.update( { _id:targetID }, { $inc : query } )

however, I might have thousands of grocery elements and find doing this loop at each update to be ugly and unoptimized.

I would like to know how to void this or why it can't be optimized.

Was it helpful?

Solution

Actually there is no way to avoid it, because there is no such command that can increment all the values inside the subdocument.

So the only way to do it is to do something like you have done:

{
    "$inc": {
        "groceries.apples" : 1, 
        "groceries.cherries" : 1,
        "groceries.prunes" : 1
    }
}

Because you do not know what are the fields exactly, you need to find them beforehand and to create the $inc statement. There is one good thing about these updates: no matter how may elements do you have, you will still need only 2 queries (find what to update and to actually perform update).

I was also thinking how to achieve a better results with a different schema, but apparently you have to cope with what you have.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top