Edits history of script submission #22472 for ' Get recently inserted documents (mongodb)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    import { MongoClient, ObjectId } from "mongodb@6";
    import { getState, setState } from "windmill-client@1";
    
    type Mongodb = {
      servers: { host: string; port: number }[];
      credential: {
        username: string;
        password: string;
        db: string;
        mechanism?: string;
      };
      db: string;
      tls: boolean;
    };
    
    /**
     * Get recently inserted documents
     * Return documents inserted since the last run, using the timestamp embedded in their ObjectId `_id`.
     */
    export async function main(
      auth: Mongodb,
      collection: string,
      database?: string,
    ) {
      const lastCheck: number = (await getState()) ?? 0;
      await setState(Date.now() / 1000);
    
      const client = await mongoClient(auth);
      try {
        return await client
          .db(database || auth.db)
          .collection(collection)
          .find({ _id: { $gt: ObjectId.createFromTime(Math.floor(lastCheck)) } })
          .toArray();
      } finally {
        await client.close();
      }
    }
    
    async function mongoClient(auth: Mongodb) {
      const hosts = auth.servers.map((s) => `${s.host}:${s.port}`).join(",");
      const options: any = { tls: auth.tls };
      if (auth.credential?.username) {
        options.auth = {
          username: auth.credential.username,
          password: auth.credential.password,
        };
        options.authSource = auth.credential.db;
        if (auth.credential.mechanism) {
          options.authMechanism = auth.credential.mechanism;
        }
      }
      const client = new MongoClient(`mongodb://${hosts}`, options);
      await client.connect();
      return client;
    }
    

    Submitted by hugo989 4 days ago