aleks.n.fedorov
aleks.n.fedorov

Reputation: 332

MongoDB update by aggregation

I want to add one filed to document as a result of aggregation.

Aggregation returns multiple items, but update updates only one.

Why only one?

Here is my code

var maxCount = db.technology.aggregate({
     $group: {
         _id:"$_id", 
          stackMax: {
             $max:"$stackTimeLine.statistics.count"}
          }
     });

 while(maxCount.hasNext()) {
    var item=maxCount.next();  
    db.technology.update(
         {_id:item._id}, 
         {$set: {'stackTimeLine.latest':item.stackMax[0]}}
    );
 }

Result:

WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 0 })

Upvotes: 0

Views: 704

Answers (2)

aleks.n.fedorov
aleks.n.fedorov

Reputation: 332

Thanks to answer of that guy solution found.

In mongo shell aggregation result has no property result

Previous answer works fine if remove result from forEach

Upvotes: 0

Disposer
Disposer

Reputation: 6371

The aggregation result is not a cursor, you cant use hasNext() and next() on it. for example, my aggregation output is

{
    "result" : [ 
        {
            "_id" : [ 
                "8"
            ],
            "count" : 474
        }, 
        {
            "_id" : [ 
                "vista"
            ],
            "count" : 414
        }, 
        {
            "_id" : [ 
                "xp"
            ],
            "count" : 5112
        }
    ],
    "ok" : 1
}

Then I use forEach() on aggregationResult.result

var aggregationResult = db.Collection.aggregate(
[
   {$group : {_id : '$ps.d.Name', count : { $sum: 1 }}}
]);

aggregationResult.result.forEach(function(item)
{
    print(item);
})

You can update your item instead of print() in forEach() function body

Upvotes: 1

Related Questions