Get recently inserted documents

Trigger script to get the newly added documents in a collection.

Script· trigger mongodb Verified

by adam186 · 12/21/2022

The script

Submitted by adam186 Deno
Verified 370 days ago
1
import {
2
  getState,
3
  setState,
4
} from "https://deno.land/x/[email protected]/mod.ts";
5
import {
6
  MongoClient,
7
  ObjectId,
8
} from "https://deno.land/x/[email protected]/mod.ts";
9

10
/**
11
 * @param data_source For example: `Cluster0`
12
 */
13
type MongodbRest = {
14
  endpoint: string;
15
  api_key: string;
16
};
17
export async function main(
18
  auth: MongodbRest,
19
  data_source: string,
20
  database: string,
21
  collection: string,
22
) {
23
  const client = new MongoClient({
24
    endpoint: auth.endpoint,
25
    dataSource: data_source,
26
    auth: { apiKey: auth.api_key },
27
  });
28
  const documents = client.database(database).collection(collection);
29
  const lastCheck = (await getState()) || 0;
30
  await setState(Date.now() / 1000);
31
  const id = ObjectId.createFromTime(lastCheck);
32
  return await documents.find({ _id: { $gt: id } });
33
}
34