DEV Community

LS
LS

Posted on • Edited on

NodeJs Mongo script query

// findAppIdsCreatedSinceFriday.js
// Usage: MONGO_URI="mongodb://..." node findAppIdsCreatedSinceFriday.js

const { MongoClient } = require("mongodb");

(async () => {
  const uri = process.env.MONGO_URI || "mongodb://localhost:27017";
  const dbName = process.env.DB_NAME
  const collName = process.env.COLL_NAME;

  // 🔒 Hardcode the Friday midnight you want
  // If midnight in New York was intended and you're in EDT (UTC-4),
  // use the equivalent UTC time (04:00:00Z).
  // Example: Sep 19, 2025 00:00 in NYC -> 2025-09-19T04:00:00Z
  const FRIDAY_ISO_UTC = "2025-09-19T04:00:00Z";

  const boundary = new Date(FRIDAY_ISO_UTC);         // JS Date
  const boundaryISO = boundary.toISOString();        // For string comparisons

  const client = new MongoClient(uri);

  try {
    await client.connect();
    const coll = client.db(dbName).collection(collName);

    console.log("Boundary (UTC):", boundaryISO);

    // ✅ Works for both BSON Date and ISO string fields, no $convert/onError
    const filter = {
      $or: [
        // Case 1: field is a BSON Date
        { "createdTimeStamp.dateTime": { $gte: boundary } },

        // Case 2: field is an ISO string; lexicographic compare is valid for ISO-8601
        {
          $and: [
            { "createdTimeStamp.dateTime": { $type: "string" } },
            { "createdTimeStamp.dateTime": { $gte: boundaryISO } }
          ]
        }
      ]
    };

    const projection = { _id: 0, applicationId: 1 };

    const cursor = coll.find(filter, { projection }).batchSize(1000);

    let count = 0;
    for await (const doc of cursor) {
      if (doc && doc.applicationId != null) {
        console.log(String(doc.applicationId));
        count++;
      }
    }
    console.log("Matched:", count);
  } catch (err) {
    console.error("Error:", err);
  } finally {
    await client.close();
  }
})();

Enter fullscreen mode Exit fullscreen mode

Top comments (0)