javascript - 使用 mongorestore 将许多文档插入临时集合

标签 javascript node.js json mongodb bson

我有一个对象数组。

const arr = [
  {
    name: 'somename',
    age: 25,
  },
  {
    name: 'othername',
    age: 15,
  },
]

当我像这样更新我的收藏时:

MyCollection.insertMany(arr);

它工作正常。该集合有 2 个对象对应于 arr 变量。

我想做的是将这些数据存储到临时集合中。就这样:

const fileName = '/tmp/some_data.bson';
const data = BSON.serialize(arr); //arr from above
await fs.writeFile(fileName, data);
await child_process.exec(`mongorestore --drop -d my-db -c my_collection_temp ${fileName}`);

这可行,但 temp 集合仅包含 1 个对象(而不是 2 个),并且该 1 个对象有 2 个字段,而每个字段又各有 2 个字段。

看起来像这样:

主要收藏:

Object1 { name: 'somename', age: 25 }
Object2 { name: 'someothername', age: 15 }

临时集合:

Object 1 {

  0: {
    name: 'somename', age: 25
  }
  1: {
    name: 'someothername', age: 15
  }

}

我知道,当我执行 mongorestore --drop -d my-db -c my_collection_temp ${fileName} 时,它只是将缓冲区转储到集合中,但我需要一种方法来忽略它并传播主集合中的对象。

换句话说,我想我想通过mongorestore来模拟insertMany

感谢任何帮助,

最佳答案

当您调用 BSON.serialize(arr) 时,您正在将数组序列化为单个 BSON 对象。

使用 bsondump 比较以这种方式生成的文件与使用 mongodump 导出该集合生成的文件。

mongorestore期望的文件格式是一系列序列化的BSON文档。

包含您帖子中的 2 个文档的 bson 文件如下所示:

00000000: 3600 0000 075f 6964 005e 4354 a93f 9947  6...._id.^CT.?.G
00000010: 050e 9bfc 0802 6e61 6d65 0009 0000 0073  ......name.....s
00000020: 6f6d 656e 616d 6500 0161 6765 0000 0000  omename..age....
00000030: 0000 0039 4000 3700 0000 075f 6964 005e  ...9@.7...._id.^
00000040: 4354 a93f 9947 050e 9bfc 0902 6e61 6d65  CT.?.G......name
00000050: 000a 0000 006f 7468 6572 6e61 6d65 0001  .....othername..
00000060: 6167 6500 0000 0000 0000 2e40 00         age........@.

请注意,第一个文档从字节 0 及其大小开始,一直延伸到字节 0x35。

第二个文档立即从字节 0x36 及其大小开始,并延伸到文件末尾的字节 0x6c。

要生成此文件,您需要依次对每个文档调用 BSON.serialize,并将字节附加到输出文件。

关于javascript - 使用 mongorestore 将许多文档插入临时集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60179411/

相关文章:

javascript - 将通用逻辑提取到 JavaScript 中的可重用函数中

java - 从 Java 运行 TypeScript 编译器

javascript - 将 ES6 类转换为 Typescript 类

javascript - 使用服务帐户访问 Google 表格时未定义回调

javascript - 如何从两个 JSON 数组获取增量?

ios - 我的 MBProgress HUD 和 JSON 方法 - 改进代码的帮助/指导

javascript - 加载时打开选项卡(有序列表)?

javascript - 如何将动态创建的 props 传递给组件?

javascript:未选中时复选框值保持为 1 而不是 0

python - 如何从数据集中删除无用元素