Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
329 views
in Technique[技术] by (71.8m points)

Query to get data from mongodb using ObjectId ("xxxxxxxxx").GetTimestamp()

I am starting in the world of mongodb.

I have the following question:

I want to find the items that were posted from date x. In the records I have no date but I can get it from this statement:

ObjectId ("5ffdc390fdd1596ca5870bec"). GetTimestamp ()

whose result is: ISODate ("2021-01-12T15: 43: 12Z")

How could I create a query that returns all the records that were created from a given date, for example from 2021-01-12? Thank you very much.!

question from:https://stackoverflow.com/questions/66050048/query-to-get-data-from-mongodb-using-objectid-xxxxxxxxx-gettimestamp

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The mongo Shell is an interactive JavaScript interface to MongoDB, so the solution by Leftium should work.

function objectIdWithTimestamp(timestamp) {
    /* Convert string date to Date object (otherwise assume timestamp is a date) */
    if (typeof(timestamp) == 'string') {
        timestamp = new Date(timestamp);
    }

    /* Convert date object to hex seconds since Unix epoch */
    var hexSeconds = Math.floor(timestamp/1000).toString(16);

    /* Create an ObjectId with that hex timestamp */
    var constructedObjectId = new ObjectId(hexSeconds + "0000000000000000");

    return constructedObjectId
}


/* Find all documents created between Jan 12th, 2021 and Jan 13th, 2021 */
db.mycollection.find({ _id: { $gt: objectIdWithTimestamp('2021/01/12'), $lt: objectIdWithTimestamp('2021/01/13')  } }); 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...