Search Documents

Script mongodb Verified

by rossumblament ยท 6/6/2022

The script

Submitted by hugo989 Bun
Verified 4 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
 * Search documents
17
 * Find documents in a collection matching a filter (with optional projection, sort, limit and skip).
18
 */
19
export async function main(
20
  auth: Mongodb,
21
  collection: string,
22
  filter?: Record<string, any>,
23
  projection?: Record<string, number>,
24
  sort?: Record<string, number>,
25
  limit?: number,
26
  skip?: number,
27
  database?: string,
28
) {
29
  const client = await mongoClient(auth);
30
  try {
31
    let cursor = client
32
      .db(database || auth.db)
33
      .collection(collection)
34
      .find(filter ?? {});
35
    if (projection) cursor = cursor.project(projection);
36
    if (sort) cursor = cursor.sort(sort);
37
    if (skip) cursor = cursor.skip(skip);
38
    if (limit) cursor = cursor.limit(limit);
39
    return await cursor.toArray();
40
  } finally {
41
    await client.close();
42
  }
43
}
44

45
async function mongoClient(auth: Mongodb) {
46
  const hosts = auth.servers.map((s) => `${s.host}:${s.port}`).join(",");
47
  const options: any = { tls: auth.tls };
48
  if (auth.credential?.username) {
49
    options.auth = {
50
      username: auth.credential.username,
51
      password: auth.credential.password,
52
    };
53
    options.authSource = auth.credential.db;
54
    if (auth.credential.mechanism) {
55
      options.authMechanism = auth.credential.mechanism;
56
    }
57
  }
58
  const client = new MongoClient(`mongodb://${hosts}`, options);
59
  await client.connect();
60
  return client;
61
}
62

Other submissions
  • Submitted by rossmccrann Deno
    Created 1420 days ago
    1
    import * as wmill from "https://deno.land/x/[email protected]/mod.ts";
    2
    import { Bson, MongoClient } from "https://deno.land/x/[email protected]/mod.ts";
    3
    
    
    4
    /*
    5
    @param: {wmill.Resource} mongodb - Resource containing mongodb connection object
    6
    example:
    7
    await client.connect({
    8
      db: "<db_name>",
    9
      tls: true,
    10
      servers: [
    11
        {
    12
          host: "<db_cluster_url>",
    13
          port: 27017,
    14
        },
    15
      ],
    16
      credential: {
    17
        username: "<username>",
    18
        password: "<password>",
    19
        db: "<db_name>",
    20
        mechanism: "SCRAM-SHA-1",
    21
      },
    22
    });
    23
    
    
    24
    @param: {object} filter - Object to filter mongodb documents
    25
    example:
    26
    { username: { $ne: null } }
    27
    
    
    28
    */
    29
    
    
    30
    export async function main(
    31
        mongodb_con: wmill.Resource<"mongodb">,
    32
        db_name: string,
    33
        collection_name: string,
    34
        filter: object
    35
    ) {
    36
        const client = new MongoClient();
    37
    
    
    38
        // Connecting to a Mongo Atlas Database
    39
        const resp = await client.connect(mongodb_con);
    40
    
    
    41
        const db = client.database(db_name);
    42
        const collection = db.collection(collection_name);
    43
    
    
    44
        const all_collection = await collection.find(filter).toArray();
    45
    
    
    46
        return (all_collection ? 'Documents Found in MongoDB' : 'Documents Not Found');
    47
    }
  • Submitted by adam186 Deno
    Created 396 days ago
    1
    import { removeObjectEmptyFields } from "https://deno.land/x/[email protected]/mod.ts";
    2
    import { MongoClient } from "https://deno.land/x/[email protected]/mod.ts";
    3
    
    
    4
    /**
    5
     * @param data_source For example: `Cluster0`
    6
     *
    7
     * @param filter For example: `{ "_id": "01234" }`
    8
     * Find out more at:
    9
     * https://www.mongodb.com/docs/manual/reference/method/db.collection.find/
    10
     */
    11
    type MongodbRest = {
    12
      endpoint: string;
    13
      api_key: string;
    14
    };
    15
    export async function main(
    16
      auth: MongodbRest,
    17
      data_source: string,
    18
      database: string,
    19
      collection: string,
    20
      filter?: Record<string, any>,
    21
      projection?: Record<string, number>,
    22
      sort?: Record<string, number>,
    23
      limit?: number,
    24
      skip?: number,
    25
    ) {
    26
      const client = new MongoClient({
    27
        endpoint: auth.endpoint,
    28
        dataSource: data_source,
    29
        auth: { apiKey: auth.api_key },
    30
      });
    31
      const documents = client.database(database).collection(collection);
    32
      return await documents.find(
    33
        filter,
    34
        removeObjectEmptyFields({ projection, sort, limit, skip }),
    35
      );
    36
    }
    37