Find all documents within last n days

前端 未结 2 1474
野的像风
野的像风 2020-11-30 13:44

My daily collection has documents like:

..
{ \"date\" : ISODate(\"2013-01-03T00:00:00Z\"), \"vid\" : \"ED\", \"san\" : 7046.25, \"izm\" : 12         


        
相关标签:
2条回答
  • 2020-11-30 14:10

    You need to run the distinct command to get all the unique dates. Below is the example. The "values" array has all the unique dates of the collection from which you need to retrieve the most recent 15 days on the client side

    db.runCommand ( { distinct: 'datecol', key: 'date' } )
    {
        "values" : [
           ISODate("2013-01-03T00:00:00Z"),
           ISODate("2013-01-04T00:00:00Z")
        ],
        "stats" : {
           "n" : 2,
           "nscanned" : 2,
           "nscannedObjects" : 2,
           "timems" : 0,
           "cursor" : "BasicCursor"
        },
        "ok" : 1
    }
    

    You then use the $in operator with the most recent 15 dates from step 1. Below is an example that finds all documents that belong to one of the mentioned two dates.

    db.datecol.find({
      "date":{
         "$in":[
            new ISODate("2013-01-03T00:00:00Z"), 
            new ISODate("2013-01-04T00:00:00Z")
          ]
      }
    })
    
    0 讨论(0)
  • 2020-11-30 14:28

    I just tested the following query against your data sample and it worked perfectly:

    db.datecol.find(
    {
        "date": 
        {
            $gte: new Date((new Date().getTime() - (15 * 24 * 60 * 60 * 1000)))
        }
    }
    ).sort({ "date": -1 })
    
    0 讨论(0)
提交回复
热议问题