0

在网上搜索之后,我无法弄清楚 BSON 是否支持一组匿名对象。我想要这个的原因是用于具有以下架构的日志记录系统

{
  ERROR_LOG: [
    {
      message: "There was an error recording the file",
      code: 1133
    },
    {
      message: "There was an error saving the file",
      code: 1135 
    }
  ],
  FILE_LOG: [
    {
      message: "File 1234.txt edited",
      code: 5445
    },
    {
      message: "File transfer success",
      code: 2332
    }
  ], 
  ... etc.
}

可能是这种模式设计效率不高。如果不支持匿名对象,我愿意接受不同模式的建议。

4

1 回答 1

1

确实如此。

在引擎盖下,文档将获得一个递增的名称“0”、“1”……但 bson 库会对您隐藏它。

如果数组中的元素,您还可以混合类型:

{
    array: [
        {
            message: "There was an error recording the file",
            code: 1133
        },
        1234,
        "etc."
    ]
}

编辑:

从这里的文档中抄袭:http: //api.mongodb.org/c/current/tutorial.html#bson

我认为您应该能够执行以下操作:

bson doc[1];

bson_init( doc );
    bson_append_start_array( b, "ERROR_LOG" );
      bson_append_start_object( doc, "0" );
        bson_append_string( doc, "message", "There was an error recording the file" );
        bson_append_int( doc, "code", 1133 );
      bson_append_finish_object( doc );
      bson_append_start_object( doc, "1" );
        bson_append_string( doc, "message", "There was an error saving the file" );
        bson_append_int( doc, "code", 1135 );
      bson_append_finish_object( doc );
    bson_append_finish_array( b );
    bson_append_start_array( b, "FILE_LOG" );
      bson_append_start_object( doc, "1" );
        bson_append_string( doc, "message", "File 1234.txt edited" );
        bson_append_int( doc, "code", 5445 );
      bson_append_finish_object( doc );
      bson_append_start_object( doc, "1" );
        bson_append_string( doc, "message", "File transfer success" );
        bson_append_int( doc, "code", 2332 );
      bson_append_finish_object( doc );
    bson_append_finish_array( b );
bson_finish( doc );

请注意,C 驱动程序欺骗了我,您确实需要跟踪数组元素的“索引”名称。

于 2013-06-10T20:38:59.040 回答