I have a collection that has two date fields and I am trying to query all records that have a difference of 15 days:
{
\"_id\" : \"someid\",
\"factoryNumbe
You need to use aggregate pipeline to get the documents
$ifNull
- to set current date if accepted date is null$addFields
- to add fields from
, fromDays
and toDays
to existing document to $redact
$redact
- match within fields and filter$project
- to exclude the fields added in $addFields
stagemongo query
db.t1.aggregate([
{$addFields : {
from : {$ifNull : ["$acceptedDate", new Date()]}
}},
{$addFields: {
fromDays : {$sum : [{$multiply : [365, {$year : "$from"}]}, {$dayOfYear : "$from"}]},
toDays : {$sum : [{$multiply : [365, {$year : "$lastVisit"}]}, {$dayOfYear : "$lastVisit"}]}
}},
{ $redact: {
$cond: {
if: {$lte : [{$subtract : ["$fromDays", "$toDays"]}, 15]},
then: "$$DESCEND",
else: "$$PRUNE"
}
}
},
{$project : {from:0, fromDays:0, toDays:0}}
])
sample collection
> db.t1.find().pretty()
{
"_id" : "someid",
"factoryNumber" : 123,
"factoryName" : "some factory name",
"visitType" : "audit",
"personelId" : "somePersonel",
"lastVisit" : ISODate("2018-10-30T00:00:00Z"),
"acceptedDate" : ISODate("2018-11-16T00:00:00Z")
}
{
"_id" : "someotherid",
"factoryNumber" : 123,
"factoryName" : "some factory name",
"visitType" : "audit",
"personelId" : "somePersonel",
"lastVisit" : ISODate("2018-10-30T00:00:00Z")
}
result with min 150 days
> db.t1.aggregate([ {$addFields : { from : {$ifNull : ["$acceptedDate", new Date()]} }}, {$addFields: { fromDays : {$sum : [{$multiply : [365, {$year : "$from"}]}, {$dayOfYear : "$from"}]}, toDays : {$sum : [{$multiply : [365, {$year : "$lastVisit"}]}, {$dayOfYear : "$lastVisit"}]} }}, { $redact: { $cond: { if: {$lte : [{$subtract : ["$fromDays", "$toDays"]}, 150]}, then: "$$DESCEND", else: "$$PRUNE" } } }, {$project : {from:0, fromDays:0, toDays:0}} ]).pretty()
{
"_id" : "someid",
"factoryNumber" : 123,
"factoryName" : "some factory name",
"visitType" : "audit",
"personelId" : "somePersonel",
"lastVisit" : ISODate("2018-10-30T00:00:00Z"),
"acceptedDate" : ISODate("2018-11-16T00:00:00Z")
}
{
"_id" : "someotherid",
"factoryNumber" : 123,
"factoryName" : "some factory name",
"visitType" : "audit",
"personelId" : "somePersonel",
"lastVisit" : ISODate("2018-10-30T00:00:00Z")
}
>
translate the mongo aggregate query into spring mongodb query