mongodb - How to add to Array and Update 'max' Value in one statement -
example
//entry 1 (value 7) { stuff : "goods" values : [7], max : 7, } //entry 2 (value : 3) { stuff : "goods" values : [7, 3], max : 7, } //entry 3 (value : 9) { stuff : "goods" values : [7, 3, 9], max : 9, } things i've tried
db.people.aggregate( {$match:{stuff:"goods"}}, {$unwind:"$values"}, {$max:1} //lost ? {$set : {max : 1}} ?? );
the .aggregate() method merely "queries" data, , not "modifiy" documents permanently in database. still want .update() make changes, , read incorrect documentation $max, "different" operator applied in "updates":
so each iteration:
db.people.drop(); db.people.update( { "stuff": "goods" }, { "$push": { "values": 7 }, "$max": { "max": 7 } }, { "upsert": true } ); // { "stuff": "goods", "values": [7], "max": 7 } db.people.update( { "stuff": "goods" }, { "$push": { "values": 3 }, "$max": { "max": 3 } }, { "upsert": true } ); // { "stuff": "goods", "values": [7,3], "max": 7 } db.people.update( { "stuff": "goods" }, { "$push": { "values": 9 }, "$max": { "max": 9 } }, { "upsert": true } ); // { "stuff": "goods", "values": [7,3,9], "max": 9 } so "that" version of $max makes modification in document "when" value supplied "greater than" present value of existing property. of course $min opposite.
whilst both of share same named operators used in "aggregation pipelines", in fact have different function. , in case, function looking for.
Comments
Post a Comment