简体   繁体   中英

Find data between dates in mongodb?

I want to get all the records which have been modified in last 10 days. In the database I've a column LastModifiedDate. Based on this I want to write filter query in MongoDB. Following is the format of collection Owner:

[
  {
    "_id": ObjectId("5b0ca634806bebc3584d9dc2"),
    "ownerKey": "WEST PIONEER LLC, ID",
    "isCorporation": true,
    "corpName": "WEST PIONEER LLC",
    "propertyMailingAddress": {
      "poBox": "",
      "street": "250 S 5TH ST",
      "house": "",
      "apartment": "2",
      "city": "BOISE",
      "state": "ID",
      "zip": "83702",
      "type": "UNKNOWN",
      "sources": [
        "SNL"
      ]
    },
    "contacts": [],
    "createDate": {
      "year": 2018,
      "month": 5,
      "day": 28
    },
    "history": [],
    "sources": [
      "SNL"
    ],
    "lastModifiedDate": "2018-05-29T01:00:36.533Z"
  }
]

I'm querying data using following query:

 db.collection.aggregate([
  {
    $project: {
      date: {
        $dateFromString: {
          dateString: "$lastModifiedDate"
        }
      }
    }
  },
  {
    $match: {
      date: {
        $gte: new Date((new Date().getTime()-(10*24*60*60*1000)))
      }
    }
  }
])

But this is not a filter query. I found a way with aggregation query, instead I want a filter query which I can execute in Mongo Compass.

In the collection document mentioned above lastModifiedDate is a string . It needs to be converted to ISODate object before being subtracted. Below query should work.

db.owners.aggregate([{$project:{"_id":1,"cdate":{$dateFromString:{"dateString":"$lastModifiedDate"}}}},{$project:{"_id":1,diff_msecs:{$subtract:[new ISODate(),"$cdate"]}}},{$project:{"_id":1,diff_days:{$divide:["$diff_msecs",1000*60*60*24]}}},{$match:{"diff_days":{"$lte":10}}}])

The initial projection converts lastModifiedDate from string to IsoDate. The second project does a subtraction from current date followed by conversion from milliseconds to days and finally, comparing if the result is less than equal to 10.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM