Edits history of script submission #22470 for ' Search Documents (mongodb)'

  • bun
    One script reply has been approved by the moderators
    Ap­pro­ved
    import { MongoClient } from "mongodb@6";
    
    type Mongodb = {
      servers: { host: string; port: number }[];
      credential: {
        username: string;
        password: string;
        db: string;
        mechanism?: string;
      };
      db: string;
      tls: boolean;
    };
    
    /**
     * Search documents
     * Find documents in a collection matching a filter (with optional projection, sort, limit and skip).
     */
    export async function main(
      auth: Mongodb,
      collection: string,
      filter?: Record<string, any>,
      projection?: Record<string, number>,
      sort?: Record<string, number>,
      limit?: number,
      skip?: number,
      database?: string,
    ) {
      const client = await mongoClient(auth);
      try {
        let cursor = client
          .db(database || auth.db)
          .collection(collection)
          .find(filter ?? {});
        if (projection) cursor = cursor.project(projection);
        if (sort) cursor = cursor.sort(sort);
        if (skip) cursor = cursor.skip(skip);
        if (limit) cursor = cursor.limit(limit);
        return await cursor.toArray();
      } finally {
        await client.close();
      }
    }
    
    async function mongoClient(auth: Mongodb) {
      const hosts = auth.servers.map((s) => `${s.host}:${s.port}`).join(",");
      const options: any = { tls: auth.tls };
      if (auth.credential?.username) {
        options.auth = {
          username: auth.credential.username,
          password: auth.credential.password,
        };
        options.authSource = auth.credential.db;
        if (auth.credential.mechanism) {
          options.authMechanism = auth.credential.mechanism;
        }
      }
      const client = new MongoClient(`mongodb://${hosts}`, options);
      await client.connect();
      return client;
    }
    

    Submitted by hugo989 4 days ago