如何在 MongoDB 中的文档中创建集合?

How to create a collection in a document in MongoDB?

我是第一次使用 MongoDB,我对 NoSQL 数据库有一些经验。

我正在尝试复制我在 Google 的 Cloud Firestore 上成功实现的行为:

我想在文档中创建一个集合。我无法使用 MongoDB 复制此行为,因为我在文档中找不到代码。请问这种行为是否可能?

提前致谢。

编辑: 这是 biometric_data 中示例文档的屏幕截图:

MongoDB 有 embedded documents 可用于存储相同的数据。您可以尝试创建一个子文档数组(每个子文档都有名称和数据 属性):

{
  name: "",
  email: "",
  ...otherFields,
  biometric_data: [
    {
      name: "glucose",
      data: {
        preferred_unit: "mg/dL"
        // Add new properties as required
      }  
    },
    {
      name: "weight",
      data: {
        preferred_unit: "KG"
      }  
    }
  ],
  ...templateData
}

但是,MongoDB 中的文档大小不能超过 16 MB。如果 biometric_data 中的字段数量有限,那么您可以使用子文档,否则您可能必须创建另一个集合来将它们存储为文档(通常首选聊天应用程序或子文档数量可能非常多的地方) .


子集合(在 Firestore 中)允许您按层次结构构建数据,使数据更易于访问。例如,用户和 posts 集合可以按以下任一方式构建:

  • 有子集
users -> {userId} -> posts -> {postId}
  • 根级集合
users -> {userId}

posts -> {postId}

尽管如果您使用根级集合,则必须在 post 的文档中添加一个 userId 以标识 post 的所有者是谁。

如果您使用 MongoDB 中的嵌套文档方式,如果任何用户决定添加许多 post,您可能会达到 16 MB 的文档限制。同样,如果 biometric_data 数组可以有很多文档,最好创建另一个集合。

Firestore's sub-collections and documents do not count towards 1 MB max doc size of parent document but nested documents in MongoDB do.

同时结帐: