1

Delete Many Documents

by
Published Dec 21, 2022
Script mongodb Verified

The script

Submitted by hugo989 Bun
Verified 6 days ago
1
import { MongoClient } from "mongodb@6";
2

3
type Mongodb = {
4
  servers: { host: string; port: number }[];
5
  credential: {
6
    username: string;
7
    password: string;
8
    db: string;
9
    mechanism?: string;
10
  };
11
  db: string;
12
  tls: boolean;
13
};
14

15
/**
16
 * Delete many documents
17
 * Delete every document matching the filter.
18
 */
19
export async function main(
20
  auth: Mongodb,
21
  collection: string,
22
  filter: Record<string, any>,
23
  database?: string,
24
) {
25
  const client = await mongoClient(auth);
26
  try {
27
    return await client
28
      .db(database || auth.db)
29
      .collection(collection)
30
      .deleteMany(filter);
31
  } finally {
32
    await client.close();
33
  }
34
}
35

36
async function mongoClient(auth: Mongodb) {
37
  const hosts = auth.servers.map((s) => `${s.host}:${s.port}`).join(",");
38
  const options: any = { tls: auth.tls };
39
  if (auth.credential?.username) {
40
    options.auth = {
41
      username: auth.credential.username,
42
      password: auth.credential.password,
43
    };
44
    options.authSource = auth.credential.db;
45
    if (auth.credential.mechanism) {
46
      options.authMechanism = auth.credential.mechanism;
47
    }
48
  }
49
  const client = new MongoClient(`mongodb://${hosts}`, options);
50
  await client.connect();
51
  return client;
52
}
53

Other submissions
  • Submitted by adam186 Deno
    Created 398 days ago
    1
    import { MongoClient } from "https://deno.land/x/[email protected]/mod.ts";
    2
    
    
    3
    /**
    4
     * @param data_source For example: `Cluster0`
    5
     *
    6
     * @param filter For example: `{ "_id": "01234" }`
    7
     * Find out more at:
    8
     * https://www.mongodb.com/docs/manual/reference/method/db.collection.deleteMany/
    9
     */
    10
    type MongodbRest = {
    11
      endpoint: string;
    12
      api_key: string;
    13
    };
    14
    export async function main(
    15
      auth: MongodbRest,
    16
      data_source: string,
    17
      database: string,
    18
      collection: string,
    19
      filter: Record<string, any>,
    20
    ) {
    21
      const client = new MongoClient({
    22
        endpoint: auth.endpoint,
    23
        dataSource: data_source,
    24
        auth: { apiKey: auth.api_key },
    25
      });
    26
      const documents = client.database(database).collection(collection);
    27
      return await documents.deleteMany(filter);
    28
    }
    29