0

I Have a mongodb with objects like this:

{
    "_id" : "7XXXXXXXXXX",
    "apps" : [ 
        {
            "id" : "e0d538e0df9a345e",
            "os" : "android",
            "token" : "f1zp-VSi7Ec:APA91bEAbfH8nMeVidkIjPrJ28WHRFDy-BhvKCQdDSdCYsylUzET9GjbPHjofCrr1NMQurinMCI4fuiF7VWNPXne-80op_h0MloK217kc1zKptdo9FTgAH5R932uDphcyB1xQ27-AFdR",
            "version" : "3.2.1",
            "build" : "8115680e",
            "timestamp" : NumberLong(1571740696818)
        }
    ]
}

How i can select objects older certain date using timestampin my case, for example older 3 month?

  • Possible duplicate of [MongoDB query for document older than 30 seconds](https://stackoverflow.com/questions/21591125/mongodb-query-for-document-older-than-30-seconds) – Matheus Hatje Oct 22 '19 at 11:01

1 Answers1

0

You can use $toDate operator in aggregation to do the desired operation,

I hope you are using mongo version 4.0+

$toDate is supported in mongo version 4.0 and on

let selectedDate = new Date();
selectedDate.setDate(d.getDate()-30); //subtracting 30 days from today's date

db.collection("your_collection_name").aggregate({$unwind:{ path: "$apps"}},
    {$addFields: { dateValue: {$toDate: "$apps.timestamp" }}}, 
    {$match: { dateValue: {$lte: selectedDate }}},
    (err, result) => {
       //perform your desired operations
    });

Explanation:

basically, I am first unwinding apps array, which will result in having a separate document of each entry in apps.

Then operate on the timestamp field in each document, and convert it into a proper date with $toDate.

Then in the next stage apply your filter with $match.

UPDATE (from comments):

as you are using mongo version 3.2 the above solution will not work.

then I think, you can opt for another approach here:

  1. Query all your documents in this particular collection, find the proper date from the timestamp field.

  2. Update each document with a new field which will now have the value of computed date from the above step, and save it.

  3. I suggest you write a migration script for the above two steps.

  4. Make sure when inserting a new document, you already add this newly computed date field.

  5. Then you can have simple query like:

    db.collection("your_collection_name").find({"app.newDateField": {$lte: {selectedDate }}}, 
        { "apps.$": 1}, 
        (err, result)=>{
    
        })
    
niranjan_harpale
  • 2,048
  • 1
  • 17
  • 21