Find all documents within last n days

前端 未结 2 1492
野的像风
野的像风 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")
          ]
      }
    })
    

提交回复
热议问题