蓝色天空.知识 · 实践 · 创造
我的收藏
在线代码实验室

运行离线文档存储 URI 解析、CRUD、排序分页、$lookup 左连接与 Promise 链实验

JAVASCRIPTWindows x64、Node.js v24.22.3 本地运行环境。explore-mongodb.mjs
explore-mongodb.mjs351 行
function matchesFilter(doc, filter = {}) {
  return Object.entries(filter).every(([k, v]) => doc[k] === v);
}

function applyProjection(doc, projection) {
  if (!projection) return structuredClone(doc);
  const out = {};
  const includeKeys = Object.entries(projection).filter(([k, v]) => k !== '_id' && v === 1);
  if (includeKeys.length > 0) {
    if (projection._id !== 0 && '_id' in doc) out._id = doc._id;
    for (const [k] of includeKeys) {
      if (k in doc) out[k] = doc[k];
    }
    return out;
  }
  for (const [k, v] of Object.entries(doc)) {
    if (projection[k] !== 0) out[k] = v;
  }
  return out;
}

class LocalCursor {
  constructor(docs, projection) {
    this._docs = docs;
    this._projection = projection;
    this._sortSpec = null;
    this._skipCount = 0;
    this._limitCount = null;
  }
  sort(spec) {
    this._sortSpec = spec;
    return this;
  }
  skip(n) {
    this._skipCount = n;
    return this;
  }
  limit(n) {
    this._limitCount = n;
    return this;
  }
  async toArray() {
    let list = this._docs.map((d) => structuredClone(d));
    if (this._sortSpec) {
      const [[field, dir]] = Object.entries(this._sortSpec);
      list.sort((a, b) => (a[field] < b[field] ? -dir : a[field] > b[field] ? dir : 0));
    }
    if (this._skipCount > 0) list = list.slice(this._skipCount);
    if (this._limitCount !== null) list = list.slice(0, this._limitCount);
    return list.map((d) => applyProjection(d, this._projection));
  }
}

class LocalCollection {
  constructor(db, name) {
    this._db = db;
    this.name = name;
    this._docs = [];
    this._seq = 1;
  }
  async insertOne(doc) {
    const _id = doc._id ?? `oid_${this._seq++}`;
    this._docs.push({ _id, ...structuredClone(doc) });
    return { acknowledged: true, insertedId: _id };
  }
  async insertMany(docs) {
    const insertedIds = {};
    for (let i = 0; i < docs.length; i++) {
      const res = await this.insertOne(docs[i]);
      insertedIds[i] = res.insertedId;
    }
    return { acknowledged: true, insertedCount: docs.length, insertedIds };
  }
  find(filter = {}, options = {}) {
    const matched = this._docs.filter((d) => matchesFilter(d, filter));
    return new LocalCursor(matched, options.projection);
  }
  async findOne(filter = {}, options = {}) {
    const hit = this._docs.find((d) => matchesFilter(d, filter));
    return hit ? applyProjection(hit, options.projection) : null;
  }
  async updateOne(filter, update) {
    const hit = this._docs.find((d) => matchesFilter(d, filter));
    if (!hit) return { matchedCount: 0, modifiedCount: 0 };
    if (update.$set) Object.assign(hit, update.$set);
    return { matchedCount: 1, modifiedCount: 1 };
  }
  async updateMany(filter, update) {
    let matchedCount = 0;
    for (const d of this._docs) {
      if (matchesFilter(d, filter)) {
        matchedCount++;
        if (update.$set) Object.assign(d, update.$set);
      }
    }
    return { matchedCount, modifiedCount: matchedCount };
  }
  async deleteOne(filter) {
    const idx = this._docs.findIndex((d) => matchesFilter(d, filter));
    if (idx === -1) return { deletedCount: 0 };
    this._docs.splice(idx, 1);
    return { deletedCount: 1 };
  }
  async deleteMany(filter) {
    const before = this._docs.length;
    this._docs = this._docs.filter((d) => !matchesFilter(d, filter));
    return { deletedCount: before - this._docs.length };
  }
  aggregate(pipeline) {
    let current = this._docs.map((d) => structuredClone(d));
    for (const stage of pipeline) {
      if (stage.$lookup) {
        const { from, localField, foreignField, as } = stage.$lookup;
        const foreignDocs = this._db.collection(from)._docs;
        current = current.map((doc) => ({
          ...doc,
          [as]: foreignDocs
            .filter((f) => f[foreignField] === doc[localField])
            .map((f) => structuredClone(f)),
        }));
      }
    }
    return { toArray: async () => current };
  }
  async drop() {
    return this._db._collections.delete(this.name);
  }
}

class LocalDb {
  constructor(name) {
    this.databaseName = name;
    this._collections = new Map();
  }
  async createCollection(name) {
    if (!this._collections.has(name)) {
      this._collections.set(name, new LocalCollection(this, name));
    }
    return this._collections.get(name);
  }
  collection(name) {
    if (!this._collections.has(name)) {
      this._collections.set(name, new LocalCollection(this, name));
    }
    return this._collections.get(name);
  }
}

class LocalMongoClient {
  constructor(uri) {
    this.uri = uri;
    this.parsed = new URL(uri);
    this._dbs = new Map();
    this.connected = false;
  }
  async connect() {
    this.connected = true;
    return this;
  }
  db(name) {
    const dbName = name || this.parsed.pathname.replace(/^\/+/, '') || 'test';
    if (!this._dbs.has(dbName)) this._dbs.set(dbName, new LocalDb(dbName));
    return this._dbs.get(dbName);
  }
  async close() {
    this.connected = false;
  }
}

async function main() {
  const client = new LocalMongoClient('mongodb://localhost:27017/appdb');
  const cases = [];

  try {
    await client.connect();
    const db = client.db();

    // Case 1: uri_parse_and_insert_find_projection
    const col1 = await db.createCollection('exampleCollection');
    await col1.insertMany([
      { name: 'Alice', age: 25, address: 'Wonderland' },
      { name: 'Bob', age: 30, address: 'Builderland' },
      { name: 'Charlie', age: 35, address: 'Chocolate Factory' },
    ]);
    const allProj = await col1
      .find({}, { projection: { _id: 0, name: 1, age: 1 } })
      .toArray();
    const aliceOnly = await col1
      .find({ name: 'Alice' }, { projection: { _id: 0, name: 1, address: 1 } })
      .toArray();
    const actual1 = {
      host: client.parsed.hostname,
      port: Number(client.parsed.port),
      dbName: db.databaseName,
      totalCount: allProj.length,
      hasIdField: '_id' in allProj[0],
      aliceMatch: aliceOnly,
    };
    const expected1 = {
      host: 'localhost',
      port: 27017,
      dbName: 'appdb',
      totalCount: 3,
      hasIdField: false,
      aliceMatch: [{ name: 'Alice', address: 'Wonderland' }],
    };
    cases.push({
      name: 'uri_parse_and_insert_find_projection',
      passed: JSON.stringify(actual1) === JSON.stringify(expected1),
      expected: expected1,
      actual: actual1,
    });

    // Case 2: update_and_delete_one_many
    const col2 = await db.createCollection('crudCol');
    await col2.insertMany([
      { name: 'Alice', age: 25, address: 'Wonderland', type: 'en' },
      { name: 'Alice', age: 28, address: 'Old Wonderland', type: 'en' },
      { name: 'Bob', age: 30, address: 'Builderland', type: 'cn' },
      { name: 'Charlie', age: 35, address: 'Chocolate Factory', type: 'en' },
    ]);
    const uOne = await col2.updateOne({ name: 'Alice' }, { $set: { age: 29 } });
    const uMany = await col2.updateMany({ name: 'Alice' }, { $set: { address: 'Updated' } });
    const dOne = await col2.deleteOne({ name: 'Alice' });
    const dMany = await col2.deleteMany({ type: 'en' });
    const rest = await col2.find({}, { projection: { _id: 0, name: 1 } }).toArray();
    const actual2 = {
      uOneMatched: uOne.matchedCount,
      uManyModified: uMany.modifiedCount,
      dOneDeleted: dOne.deletedCount,
      dManyDeleted: dMany.deletedCount,
      remainingNames: rest.map((d) => d.name),
    };
    const expected2 = {
      uOneMatched: 1,
      uManyModified: 2,
      dOneDeleted: 1,
      dManyDeleted: 2,
      remainingNames: ['Bob'],
    };
    cases.push({
      name: 'update_and_delete_one_many',
      passed: JSON.stringify(actual2) === JSON.stringify(expected2),
      expected: expected2,
      actual: actual2,
    });

    // Case 3: sort_limit_skip_pagination
    const col3 = await db.createCollection('pageCol');
    await col3.insertMany([
      { name: 'Alice', age: 25 },
      { name: 'Bob', age: 30 },
      { name: 'Charlie', age: 35 },
      { name: 'Dave', age: 20 },
      { name: 'Eve', age: 22 },
    ]);
    const asc = await col3.find().sort({ age: 1 }).toArray();
    const desc = await col3.find().sort({ age: -1 }).toArray();
    const top3 = await col3.find().limit(3).toArray();
    const page2 = await col3.find().skip(2).limit(2).toArray();
    const actual3 = {
      ascAges: asc.map((d) => d.age),
      descAges: desc.map((d) => d.age),
      limit3Names: top3.map((d) => d.name),
      skip2Limit2Names: page2.map((d) => d.name),
    };
    const expected3 = {
      ascAges: [20, 22, 25, 30, 35],
      descAges: [35, 30, 25, 22, 20],
      limit3Names: ['Alice', 'Bob', 'Charlie'],
      skip2Limit2Names: ['Charlie', 'Dave'],
    };
    cases.push({
      name: 'sort_limit_skip_pagination',
      passed: JSON.stringify(actual3) === JSON.stringify(expected3),
      expected: expected3,
      actual: actual3,
    });

    // Case 4: lookup_left_join_drop_and_promise_chain
    const orders = db.collection('orders');
    const products = db.collection('products');
    await orders.insertMany([
      { _id: 1, product_id: 101, quantity: 2 },
      { _id: 2, product_id: 102, quantity: 1 },
      { _id: 3, product_id: 103, quantity: 4 },
      { _id: 4, product_id: 999, quantity: 1 },
    ]);
    await products.insertMany([
      { _id: 101, name: 'Product A', price: 50 },
      { _id: 102, name: 'Product B', price: 70 },
      { _id: 103, name: 'Product C', price: 100 },
      { _id: 104, name: 'Product D', price: 120 },
    ]);
    const joined = await orders
      .aggregate([
        {
          $lookup: {
            from: 'products',
            localField: 'product_id',
            foreignField: '_id',
            as: 'productDetails',
          },
        },
      ])
      .toArray();

    const dropOk = await db.collection('pageCol').drop();

    const docsCol = db.collection('documents');
    const ins = await docsCol.insertOne({ site: 'mbsky.example' });
    const afterIns = await docsCol.find({}).toArray();
    await docsCol.updateOne({ _id: ins.insertedId }, { $set: { site: 'updated.example' } });
    const afterUpd = await docsCol.findOne({ _id: ins.insertedId });
    await docsCol.deleteOne({ _id: ins.insertedId });
    const afterDel = await docsCol.find({}).toArray();

    const actual4 = {
      order1Product: joined[0].productDetails[0].name,
      unmatchedOrderDetailsCount: joined[3].productDetails.length,
      dropOk,
      promiseChainAfterInsertCount: afterIns.length,
      promiseChainUpdatedSite: afterUpd.site,
      promiseChainFinalCount: afterDel.length,
    };
    const expected4 = {
      order1Product: 'Product A',
      unmatchedOrderDetailsCount: 0,
      dropOk: true,
      promiseChainAfterInsertCount: 1,
      promiseChainUpdatedSite: 'updated.example',
      promiseChainFinalCount: 0,
    };
    cases.push({
      name: 'lookup_left_join_drop_and_promise_chain',
      passed: JSON.stringify(actual4) === JSON.stringify(expected4),
      expected: expected4,
      actual: actual4,
    });
  } finally {
    await client.close();
  }

  console.log(JSON.stringify({ version: process.version, cases }));
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
本例需在 Windows x64、Node.js v24.22.3 本地运行环境。 中运行,请复制源码、保存文件或下载工程包后在本地执行验证。
运行说明与环境独立工程

运行环境:Windows x64、Node.js v24.22.3 本地运行环境。

入口文件:projects/nodejs-mongodb-lab/explore-mongodb.mjs

本地运行步骤快速上手
  1. 点击上方“保存源码”保存为 explore-mongodb.mjs,或下载右侧课程工程包。
  2. 确认本地已准备 Windows x64、Node.js v24.22.3 本地运行环境。。
  3. 按对应章节命令执行,结合正文核对实际输出。
附件与关联工程包下载

下载课程关联工程包:Node.js

课程关联工程包(登记关联1章) · 含当前章节或实例 · mbskycom202612a1059.zip

下载课程关联工程包:Node.js

课程关联工程包(登记关联38章) · 含当前章节或实例 · mbskycom202612a1041.zip
SITE SEARCH

搜索教程、工具与资讯

热门搜索

JavaScriptJSON格式化正则表达式AI 编程AI 翻译AI导航专题标签
Esc 关闭

欢迎登录蓝色天空网

使用会员账号,继续你的学习