2

I want to run a query which gets all the documents which has the 'active' field as true and run a custom function on them which checks if the 'date' field inside the document is older than 10 days. If both of them are true then it will make the active field to false.

This is how my current code looks like:

db.ad.find( { $and : [ // Check if active is true and the $where clause also equals to true
    { 'active' : true
    },
    { '$where' : function() { // Custom compare function
            var date = new Moment(this.date); // gets the date from the current document
            var date2 = new Moment();
            return Math.abs(date.diff(date2, 'days')) > 10;
        }
    }
]},
function(err, result) {
    // How to update the document here?
}
);

Can anyone tell me how to update the documents after the find query?

shash7
  • 1,719
  • 1
  • 18
  • 20

2 Answers2

2

Use the update() method with the $set modifier operator to update the active field. As with the update query object, you can set a date object to ten days previous by subtracting ten from the date:

var d = new Date();
d.setDate(d.getDate() - 10);
var query = { /* query object to find records that need to be updated */
        "active": true,
        "date": { "$lte": d }
    },
    update = { /* the replacement object */
        "$set": {
            "active": false
        }
    },
    options = { /* update all records that match the query object, default is false (only the first one found is updated) */
        "multi": true
    };

db.ad.update(query, update, options, callback);

-- EDIT --

Using momentjs library, getting the date 10 days ago can be as simple as (with the add() method)

d = moment().add(-10, 'days');

or using the subtract() method

d = moment().subtract(10, 'days');
chridam
  • 100,957
  • 23
  • 236
  • 235
1

Depending on what you want to do in the update you can use db.collection.update and set the multi flag to true. Let's say you want to set a member called olderThan10Days to True. You would use the update instead of find like this:

db.ad.update(
{
   active: True,
   date: {
       $lte: "date10DaysAgo"
   }
}

},
{
   $set : { olderThan10Days : True}
},
{
   multi: True
})

Otherwise you can just iterate through your result variable and update or save it individually.

Pio
  • 4,044
  • 11
  • 46
  • 81