How to get inserted documents information within last 2 or 3 days on stand alone server?

Hi Team,
I want to check all inserted documents for specific time interval. if my server is stand-alone server then how can I get those documents. I am using mongodb atlas and its not a on-prem server.
I believe if we have replicated nodes then we can get inserted document detail from oplog.rs collection.
Note:- I want all documents in a database inserted irrespective of collection count.

Hi @Shubhada_Patil and welcome to the MongoDB community forum.

The most efficient way to do this would be to use include createdAt field in the document while inserting into the collection. For example,

db.collection.insertOne({
    // other fields
    createdAt: new Date()
});

then you can use this field value to filter the data between the dates.

If the above is not possible, there could be another workaround to use ObjectIDs which are auto-created at inserting as this contains A 4-byte timestamp, representing the ObjectId’s creation, measured in seconds since the Unix epoch.

You can try using the below script to find data between the dates.

function getObjectIdFromDate(date) {
    return ObjectId(Math.floor(date.getTime() / 1000).toString(16) + "0000000000000000");
}

var startDate = new Date("2015-01-01T00:00:00Z");
var endDate = new Date("2017-01-01T23:59:59Z");

//finding data inserted between in two years

var startObjectId = getObjectIdFromDate(startDate);
var endObjectId = getObjectIdFromDate(endDate);

var cursor = db.movies.find({
    _id: {
        $gte: startObjectId,
        $lt: endObjectId
    }
});

while (cursor.hasNext()) {
    printjson(cursor.next());
}

Let us know if the above method works for you.

Best Regards
Aasawari

Hi @Aasawari ,
Thanks for your help. your solution is helpful where ObjectId is present. but we have some collection without ObjectId field.
Below is the sample document.
{
“_id”: 7,
“businessLocationTypeId”: 2,
“subType”: “Bariatrics”
}
so we have not inserted createdAt field at the time of creation. is there any way to find date and time for such documents?