Find Document by Id

Script mongodb Verified

by maximelambercier ยท 6/6/2022

The script

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

7
/**
8
 * @param data_source For example: `Cluster0`
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
  document_id: string,
20
  projection?: Record<string, number>,
21
) {
22
  const client = new MongoClient({
23
    endpoint: auth.endpoint,
24
    dataSource: data_source,
25
    auth: { apiKey: auth.api_key },
26
  });
27
  const db = client.database(database);
28
  return await db
29
    .collection(collection)
30
    .findOne(
31
      { _id: new ObjectId(document_id) },
32
      removeObjectEmptyFields({ projection }),
33
    );
34
}
35

Other submissions
  • Submitted by rossmccrann Deno
    Created 1393 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
    
    
    25
    export async function main(
    26
        mongodb_con: wmill.Resource<"mongodb">,
    27
        db_name: string,
    28
        collection_name: string,
    29
        objectId: string
    30
    ) {
    31
        const client = new MongoClient();
    32
    
    
    33
        // Connecting to a Mongo Atlas Database
    34
        const resp = await client.connect(mongodb_con);
    35
    
    
    36
        const db = client.database(db_name);
    37
        const collect = db.collection(collection_name);
    38
    
    
    39
        const collect_single = await collect.findOne({ _id: objectId });
    40
    
    
    41
        return (collect_single ? 'Document Found in MongoDB' : 'Document Not Found');
    42
    }
    43