1

Update a Document

by
Published Jun 6, 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
 * Update a document
17
 * Update the first document matching the filter. `update` uses update operators,
18
 * e.g. `{ "$set": { "field": "value" } }`.
19
 */
20
export async function main(
21
  auth: Mongodb,
22
  collection: string,
23
  filter: Record<string, any>,
24
  update: Record<string, any>,
25
  upsert?: boolean,
26
  database?: string,
27
) {
28
  const client = await mongoClient(auth);
29
  try {
30
    return await client
31
      .db(database || auth.db)
32
      .collection(collection)
33
      .updateOne(filter, update, { upsert: upsert ?? false });
34
  } finally {
35
    await client.close();
36
  }
37
}
38

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

Other submissions
  • Submitted by rossmccrann Deno
    Created 1422 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
    
    
    26
    export async function main(
    27
        mongodb_con: wmill.Resource<"mongodb">,
    28
        db_name: string,
    29
        collection_name: string,
    30
        data: object,
    31
        _id: string
    32
    
    
    33
    ) {
    34
        const client = new MongoClient();
    35
    
    
    36
        // Connecting to a Mongo Atlas Database
    37
        const resp = await client.connect(mongodb_con);
    38
    
    
    39
        const db = client.database(db_name);
    40
        const collection = db.collection(collection_name);
    41
    
    
    42
        const { matchedCount, modifiedCount, upsertedId } = await collection.updateOne(
    43
            { _id: ObjectID(_id), },
    44
            { $set: data },
    45
        );
    46
    
    
    47
        return ({ matchedCount: matchedCount, modifiedCount: modifiedCount, upsertedId: upsertedId });
    48
    }
  • 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
     *
    8
     * @param upsert If `true` and no documents match the `filter`,
    9
     * then a new document will be created with the values of `document`.
    10
     * Default is `false`.
    11
     */
    12
    type MongodbRest = {
    13
      endpoint: string;
    14
      api_key: string;
    15
    };
    16
    export async function main(
    17
      auth: MongodbRest,
    18
      data_source: string,
    19
      database: string,
    20
      collection: string,
    21
      filter: Record<string, any>,
    22
      document: Record<string, any>,
    23
      upsert?: boolean,
    24
    ) {
    25
      const client = new MongoClient({
    26
        endpoint: auth.endpoint,
    27
        dataSource: data_source,
    28
        auth: { apiKey: auth.api_key },
    29
      });
    30
      const docs = client.database(database).collection(collection);
    31
      upsert = typeof upsert === "boolean" ? upsert : undefined;
    32
      return await docs.updateOne(filter, document, { upsert });
    33
    }
    34