Get diff Year in MongoDb
Aug 14, 2023
db.embryosTransfer.find().forEach(function (doc1) {
var doc2 = db.users.findOne({ _id: doc1.patientUserId });
if (doc2 != null) {
let date1 = new Date(doc2.dateOfBirth);
let date2 = new Date(doc1.date);
let diffTime = Math.abs(date2 - date1);
let diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24));
let diffYears = Math.floor(diffTime / (1000 * 60 * 60 * 24 * 365));
let daysLastYear = diffDays - ( diffYears * 365);
if( daysLastYear>= 180){
diffYears +=1;
}
db.embryosTransfer.update({'_id' : doc1._id}, [ { $set: { "age" :diffYears} } ]);
}
});