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

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

报告相同问题?

悬赏问题

  • ¥15 AIC3204的示例代码有吗,想用AIC3204测量血氧,找不到相关的代码。
  • ¥20 CST怎么把天线放在座椅环境中并仿真
  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型