如何在php中序列化反序列化mongo文档?

时间:2018-11-23 13:58:19

标签: php mongodb

我想将一些mongo文档保存到json文件中(就像备份一样)。因此,当我尝试执行此操作时,我总是将json与:

"_id":{"$oid":"..."}

"createdAt":{"$date":{"$numberLong":"...."}}}

那么,我需要做什么或如何获得正确的“ _id”和“ createdAt”?我的意思是应该是ObjectId和ISODate。

"_id" : ObjectId(""),
"createdAt" : ISODate("2016-05-..."),

1 个答案:

答案 0 :(得分:1)

序列化/反序列化bson的一种干净方法是扩展模型/类以实现MongoDB\BSON\Persistable

class MyModel implements MongoDB\BSON\Persistable{

    public function bsonSerialize()
    {
        return [
            'field1' => $this->field1,
            'date1' => new UTCDateTime($this->dateTimeDate->getTimestamp()*1000)
        ];
    }

    public function bsonUnserialize(array $data){
         $this->field1 = $data['field1'];
         $this->dateTimeDate = $data['date1']->toDateTime();
    }
}

具有该实现的序列化是“自动”完成的,因此您可以按以下方式使用它:

//get document from mongodb
 $document = $this->mycollection->findOne(array('id' => $id->toString())); //parsed class MyModel is returned.

//insert document into mongodb
$this->mycollection->insertOne($myentity); //class is mapped to bson

要将类序列化为JSON,可以另外实现接口JsonSerializable并使用json_decode / json_encode