deno.land / x / mongo@v0.30.1

src/
tests/
import * as mongo from "https://deno.land/x/mongo@v0.30.1/mod.ts";

Classes

Binary
Bson.Binary
Bson.BSONError
Bson.BSONRegExp

A class representation of the BSON RegExp type.

Bson.BSONSymbol

A class representation of the BSON Symbol type.

Bson.BSONTypeError
Bson.BufReader

BufReader implements buffering for a Reader object.

Bson.Code

A class representation of the BSON Code type.

Bson.DBRef

A class representation of the BSON DBRef type.

Bson.Decimal128

A class representation of the BSON Decimal128 type.

Bson.Double

A class representation of the BSON Double type.

Bson.Int32

A class representation of a BSON Int32 type.

Bson.Long

A class representing a 64-bit integer

Bson.MaxKey

A class representation of the BSON MaxKey type.

Bson.MinKey

A class representation of the BSON MinKey type.

Bson.ObjectId

A class representation of the BSON ObjectId type.

Bson.Timestamp
Bson.UUID

A class representation of the BSON UUID type.

BSONRegExp

A class representation of the BSON RegExp type.

BSONSymbol

A class representation of the BSON Symbol type.

Code

A class representation of the BSON Code type.

Collection
Database
DBRef

A class representation of the BSON DBRef type.

Decimal128

A class representation of the BSON Decimal128 type.

Double

A class representation of the BSON Double type.

GridFSBucket
Int32

A class representation of a BSON Int32 type.

Long

A class representing a 64-bit integer

MaxKey

A class representation of the BSON MaxKey type.

MinKey

A class representation of the BSON MinKey type.

MongoClient
ObjectId

A class representation of the BSON ObjectId type.

Timestamp
UUID

A class representation of the BSON UUID type.

Variables

Bson.BSON_BINARY_SUBTYPE_DEFAULT

Binary Default Type @internal

Bson.BSON_INT32_MAX
Bson.BSON_INT32_MIN
Bson.crypto

An wrapper for WebCrypto adding support for additional non-standard algorithms, but delegating to the runtime WebCrypto implementation whenever possible.

Bson.JS_INT_MAX

Any integer up to 2^53 can be precisely represented by a double.

Bson.JS_INT_MIN

Any integer down to -2^53 can be precisely represented by a double.

Bson.LongWithoutOverridesClass

Functions

Bson.b64.decode

Decodes a given RFC4648 base64 encoded string

Bson.b64.encode

CREDIT: https://gist.github.com/enepomnyaschih/72c423f727d395eeaa09697058238727 Encodes a given Uint8Array, ArrayBuffer or string into RFC4648 base64 representation

Bson.calculateObjectSize

Calculate the bson size for a passed in Javascript object.

Bson.deferred

Creates a Promise with the reject and resolve functions placed as methods on the promise object itself. It allows you to do:

Bson.deserialize

Deserialize data as BSON.

Bson.deserializeStream

Deserialize stream data as BSON documents.

Bson.EJSON.deserialize

Deserializes an Extended JSON object into a plain JavaScript object with native/BSON types

Bson.EJSON.isBSONType
Bson.EJSON.parse

Parse an Extended JSON string, constructing the JavaScript value or object described by that string.

Bson.EJSON.serialize

Serializes an object to an Extended JSON string, and reparse it as a JavaScript object.

Bson.EJSON.stringify

Converts a BSON document to an Extended JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.

Bson.hex.decode

Decodes src into src.length / 2 bytes. If the input is malformed, an error will be thrown.

Bson.hex.encode

Encodes src into src.length * 2 bytes.

Bson.serialize

Serialize a Javascript object.

Bson.serializeWithBufferAndIndex

Serialize a Javascript object using a predefined Buffer and index into the buffer, useful when pre-allocating the space for serialization.

Bson.setInternalBufferSize

Sets the size of the internal serialization buffer.

Bson.writeAll

Write all the content of the array buffer (arr) to the writer (w).

deno_mongo

deno_mongo is a MongoDB database driver developed for Deno. supports Deno Deploy as well.

tag Build Status license Discord server

Import

Replace LATEST_VERSION with current latest version

import {
  Bson,
  MongoClient,
} from "https://deno.land/x/mongo@LATEST_VERSION/mod.ts";

Connect

const client = new MongoClient();

// Connecting to a Local Database
await client.connect("mongodb://127.0.0.1:27017");

// Connecting to a Mongo Atlas Database
await client.connect({
  db: "<db_name>",
  tls: true,
  servers: [
    {
      host: "<db_cluster_url>",
      port: 27017,
    },
  ],
  credential: {
    username: "<username>",
    password: "<password>",
    db: "<db_name>",
    mechanism: "SCRAM-SHA-1",
  },
});

// Connect using srv url
await client.connect(
  "mongodb+srv://<username>:<password>@<db_cluster_url>/<db_name>?authMechanism=SCRAM-SHA-1",
);

Access Collection

// Defining schema interface
interface UserSchema {
  _id: ObjectId;
  username: string;
  password: string;
}

const db = client.database("test");
const users = db.collection<UserSchema>("users");

Insert

const insertId = await users.insertOne({
  username: "user1",
  password: "pass1",
});

const insertIds = await users.insertMany([
  {
    username: "user1",
    password: "pass1",
  },
  {
    username: "user2",
    password: "pass2",
  },
]);

Find

const user1 = await users.findOne({ _id: insertId });

const all_users = await users.find({ username: { $ne: null } }).toArray();

// find by ObjectId
const user1_id = await users.findOne({
  _id: new ObjectId("SOME OBJECTID STRING"),
});

Count

const count = await users.countDocuments({ username: { $ne: null } });

const estimatedCount = await users.estimatedDocumentCount({
  username: { $ne: null },
});

Aggregation

const docs = await users.aggregate([
  { $match: { username: "many" } },
  { $group: { _id: "$username", total: { $sum: 1 } } },
]).toArray();

Update

const { matchedCount, modifiedCount, upsertedId } = await users.updateOne(
  { username: { $ne: null } },
  { $set: { username: "USERNAME" } },
);

const { matchedCount, modifiedCount, upsertedId } = await users.updateMany(
  { username: { $ne: null } },
  { $set: { username: "USERNAME" } },
);

Replace

const { matchedCount, modifiedCount, upsertedId } = await users.replaceOne(
  { username: "a" },
  {
    username: "user1",
    password: "pass1",
  }, // new document
);

Delete

const deleteCount = await users.deleteOne({ _id: insertId });

const deleteCount2 = await users.deleteMany({ username: "test" });

Cursor methods

const cursor = users.find();

// Skip & Limit
cursor.skip(10).limit(10);

// iterate results
for await (const user of cursor) {
  console.log(user);
}

// or save results to array (uses more memory)
const users = await cursor.toArray();

GridFS

// Upload
const bucket = new GridFSBucket(db);
const upstream = bucket.openUploadStream("test.txt");

const writer = upstream.getWriter();
writer.write(fileContents);

await writer.close();

// Download
const file = await new Response(bucket.openDownloadStream(id)).text();

Community Resources

Tools

Examples

  • deno-deploy-mongo A simple app with Deno, MongoDB and oak deployed on Deno Deploy and MongoDB Atlas
  • deno_rest A simple oak based boilerplate for RESTful apis using deno_mongo

Contributing

Local testing with Docker

  1. docker run -d -p 27017:27017 mongo
  2. deno test -A
mongo
MongoDB driver for Deno
GitHub Stars
432

Version Info

Tagged at
a week ago

External Dependencies