2

I want to find all the documents with in collection that got created in last three months (within 3 months only and not older ones).

Sample document :

Cause i thought it would be more reliable.But if you feel that's it's safe you can guide me using ce field of document too.

Thanks in advance

Pawan Saxena
  • 521
  • 1
  • 4
  • 14

1 Answers1

3

If I understand your question corectly then your chosen comparison field (ce) contains the number of seconds since the epoch. If so, then you cannot directly compare that with a Javascript Date value.

Instead, you'll have to convert the Javascript Date object's time value to a number of seconds and then compare against that value.

For example:

var threeMonthsAgo = new Date();
threeMonthsAgo.setMonth(threeMonthsAgo.getMonth() - 3);
var threeMonthsAgoInSeconds = threeMonthsAgo.getTime() / 1000
db.collection.find({ 
    ce: { $gte: threeMonthsAgoInSeconds } 
})

This conversion of millis to seconds is subject to some inaccuracy and if this inaccuracy is unacceptable then I think the solution is to store ce as the number of milliseconds since the epoch.

If ce stored the number of millis then it could be directly compared with the value of the calculated "3 months ago" Javascript date.

However, the above example does not require you to convert ce into millis. All I'm saying is that comparing a seconds value with a calculated value which is derived from millis introduces some minimal potential for inaccuracy. It's possible that this won't matter in your use case but if it does then the only way to resolve it is to compare like with like i.e. millis against millis.

glytching
  • 44,936
  • 9
  • 114
  • 120
  • thanks mate but problem is that i do have a field to store creation timestamp and it's stored as timstamp like 1523154556, note that it have 10 digits (meaning seconds). – Pawan Saxena Mar 19 '18 at 17:29
  • sorry it's not working , it's giving me empty results. – Pawan Saxena Mar 19 '18 at 17:32
  • Can you update your question to _show_ us an example document? The key parts of interest are (1) the name of your 'creation timestamp' field and (2) how that field is populated. – glytching Mar 19 '18 at 17:33
  • My goal is to give preference to my own creation field : ce – Pawan Saxena Mar 19 '18 at 17:43
  • thanks mate but since the collection is humungous (50 million records), i am not at the liberty to convert the ce field into millis, and since the inaccuracy here is completely unacceptable cause it's related with some revenue...is there any workaround you can think of – Pawan Saxena Mar 19 '18 at 17:56
  • I have updated the answer to make clear that I am not saying that you must convert `ce` into millis. – glytching Mar 19 '18 at 17:59