ds342222 2017-04-08 18:54
浏览 42
已采纳

MongoDB / PHP在嵌入式文档中独立设置类型映射

I have had a good look around but I can't seem to find the answer to my question. If I have the following document with several different embedded document types, how do I set the type map for each document independently of the others?

{
    _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" }
    ]
}

I know how I can set a type map for all embedded documents using the PHP7 MongoDB driver:

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

This will unserialize all of the embedded documents into instances of the SomeOtherObj class, and the root document into the RootObj class. What I really want to do is specify this for each type of embedded document.

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

Can it be done?

  • 写回答

1条回答 默认 最新

  • dougu5886 2017-04-08 19:35
    关注

    I've had a good read through and found a class I didn't know existed before, which allows MongoDB to remember which class each object belongs to without having to explicitly set a type map. I changed my class objects that implemented MongoDB\BSON\Serializable and MongoDB\BSON\Unserializable to just implementing MongoDB\BSON\Persistable.

    MongoDB\BSON\Persistable injects a __pclass variable into the document, which is a reference to the class that was used during serialization. It uses that reference to decide which class to unserialize into and overrides the type map.

    MongoDB\BSON\Persistable

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大