简体   繁体   中英

Mongo DB Date Difference and and query condtion in same query in Java Mongo Template

Hi guys i trying to make query like following

update date more than 2 hours, then status=inprogress get all tasks. query sample date is

{
    "_id" : "ATK-l64KC3vm",
    "nodeid" : "NOD-AJaodNfH",
    "accountid" : "d983356b-7fde-4683-9ba5-e6b6f5a0680d",
    "applicationid" : "59a57cb7-7d67-4d55-bd6c-ff537bcf05d6",
    "avmdepid" : "DEP-1aa81899",
    "instanceId" : "INS-YNXr1ldB",
    "cloudinstanceid" : "",
    "inputxml" : "",
    "status" : "No value present",
    "callbackUrl" : "",
    "callbackMethod" : "PUT",
    "callbackInput" : "<input></input>",
    "priority" : "false",
    "type" : "datapush",
    "createdDt" : ISODate("2020-05-20T05:56:55.467Z"),
    "updatedDt" : ISODate("2020-05-20T05:56:55.478Z"),
    "agentid" : "IAG-R2koJqnk"
}

pls help to make this query in java Mongo template aggregation filter

First, we can use $addFields or $set to add new field (temporary) to document which will hold time difference. (in milliseconds)

db.collectionName.aggregate([
  {"$addFields": {"timeDiff": { $subtract: [new Date(), "$updatedDt"]}}}
]);

Now, we will use those fields to filtering records using $match

db.collectionName.aggregate([
 {"$addFields": {"timeDiff": { $subtract: [new Date(), "$updatedDt"]}}},
 {$match: {"timeDiff":{ $gte: 2* 60* 60* 1000},"status":"in-progress"}}
]);

Now, we can remove additionally added field using $project

db.collectionName.aggregate([
 {"$addFields": {"timeDiff": { $subtract: [new Date(), "$updatedDt"]}}}, 
 {$match:{"timeDiff":{$gte: 2* 60* 60* 1000},"status":"in-progress"}},
 {$project: {"timeDiff":0}}
]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM