Query the string type Date in mongodb

前端 未结 3 720
醉梦人生
醉梦人生 2021-01-14 05:07

This is my query in mongodb

db.order.find ({\"ublExtensions.ublExtensions.extensionContent.Metadata
                .ModificationTime\": \"2012-02-04T01:58:2         


        
相关标签:
3条回答
  • 2021-01-14 05:17

    I would recommend storing your dates as Date or ISODate on MongoDB since it would ease your life :)

    If not possible, then on the client side (programming language specific driver) you should be able to parse the string to the appropiate Date type.

    However, if you need your query to run on mongo shell, you could follow an strategy similar as described at Mongo Cookbook

    1) Creating a var with today's date and yesterday's date:

    >var today = new Date();
    >today
    ISODate("2012-11-26T22:12:03.870Z")
    >var yesterday = new Date()
    >yesterday.setDate(today.getDate() - 1)
    >yesterday
    ISODate("2012-11-25T22:12:03.870Z")
    

    2) Form a query for finding documents within a 24 hours period

    >db.order.find( { "ublExtensions.ublExtensions.extensionContent.Metadata.ModificationTime" : { $gte : yesterday, $lt : today } } )
    
    0 讨论(0)
  • 2021-01-14 05:32

    Mongodb stores its date objects in a bson format like: {$date: 1329415205151}

    If you decide to store it in a string format, then it is the client-side responsibility to filter and process this value as mongo treats it like a string. You can convert your strings to date objects by referring to this other SO question: How do I convert a property in MongoDB from text to date type?

    Its been widely recommended to either store all your dates in UTC, or, a consistent timezone possibly related to the local datacenter, and then convert your date values to the proper local timezone on the client.

    You can store whatever Date value you want. The value of the date and the format of the date are two separate issues. If your constraints require you to store that string-based date format in the document, it would be recommended to also store a $date object as well at the time of update.

    0 讨论(0)
  • 2021-01-14 05:37

    Why can't you just use $gt query and for comparing time you can use Date.now() and from that Date.now() you can use previous date, like if current date is "2017-05-16T02:08:48.419+05:30" then you will write the query

    db.collection.find({"createdAt": { $gte : new ISODate("2017-05-15T02:08:48.419+05:30") }})
    
    0 讨论(0)
提交回复
热议问题