简体   繁体   English

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

[英]MongoDB/PHP set type map independently on embedded documents

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 : 我知道如何使用PHP7 MongoDB驱动程序为所有嵌入式文档设置类型映射:

$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. 这会将所有嵌入的文档反序列化为SomeOtherObj类的实例,并将根文档反序列化为RootObj类。 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? 能做到吗

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. 我已经通读了一个很好的文章,发现了一个以前不存在的类,它使MongoDB无需记住设置类型映射即可记住每个对象所属的类。 I changed my class objects that implemented MongoDB\\BSON\\Serializable and MongoDB\\BSON\\Unserializable to just implementing MongoDB\\BSON\\Persistable . 我将实现MongoDB\\BSON\\SerializableMongoDB\\BSON\\Unserializable类对象更改为仅实现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. MongoDB\\BSON\\Persistable__pclass变量注入到文档中,该变量是对序列化过程中使用的类的引用。 It uses that reference to decide which class to unserialize into and overrides the type map. 它使用该引用来确定要反序列化到的类并覆盖类型映射。

MongoDB\\BSON\\Persistable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM