【问题标题】:Using mongorestore to insert many documents into a temp collection使用 mongorestore 将许多文档插入临时集合
【发布时间】:2020-02-12 00:33:54
【问题描述】:

我有一个对象数组。

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

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

MyCollection.insertMany(arr);

它工作正常。该集合有 2 个 Objects 对应于 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

感谢您的帮助,

【问题讨论】:

    标签: javascript node.js json mongodb bson


    【解决方案1】:

    当您调用 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,并将字节附加到输出文件中。

    【讨论】:

      猜你喜欢
      • 2016-10-14
      • 1970-01-01
      • 2020-09-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-28
      相关资源
      最近更新 更多