【问题标题】:MongoDB/PHP set type map independently on embedded documentsMongoDB/PHP 在嵌入文档上独立设置类型映射
【发布时间】:2017-09-04 01:51:39
【问题描述】:

我环顾四周,但似乎找不到问题的答案。如果我有以下具有几种不同嵌入文档类型的文档,如何独立于其他文档设置每个文档的类型映射?

{
    _id : ObjectId("bf98321fba31233"),
    name : "Example", 
    comments : [
         comment : { _id : ObjectId("bf98321fba31233"), text : "Example comment type" },
         comment : { _id : ObjectId("bf98321fba31233"), text : "Another example" }
    ],
    attachments : [
         attachment : { _id : ObjectId("bf98321fba31233"), url : "/var/www/blah/foo" },
         attachment : { _id : ObjectId("bf98321fba31233"), url : "/var/www/blah/bar" }
    ]
}

我知道如何使用PHP7 MongoDB driver 为所有嵌入文档设置类型映射:

$cursor = $mongo->executeQuery("TestDB.TestCollection", new MongoDB\Driver\Query([]));
$cursor->setTypeMap(['root' => 'RootObj', 'document' => 'SomeOtherObj']);

这会将所有嵌入文档反序列化为 SomeOtherObj 类的实例,并将根文档反序列化为 RootObj 类。我真正想做的是为每种类型的嵌入文档指定这个。

$cursor->setTypeMap(['root' => 'RootObj', 'comment' => 'CommentObj', 'attachment' => 'AttachmentObj']);

可以吗?

【问题讨论】:

  • 您描述的功能尚未实现。相关的跟踪单是PHPC-314
  • @jmikola 感谢提醒

标签: php mongodb php-7


【解决方案1】:

我仔细阅读并发现了一个我以前不知道存在的类,它允许 MongoDB 记住每个对象属于哪个类,而无需显式设置类型映射。我将实现MongoDB\BSON\SerializableMongoDB\BSON\Unserializable 的类对象更改为仅实现MongoDB\BSON\Persistable

MongoDB\BSON\Persistable__pclass 变量注入到文档中,该变量是对序列化期间使用的类的引用。它使用该引用来决定要反序列化到哪个类并覆盖类型映射。

MongoDB\BSON\Persistable

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多