MongoDBRef 类

(PECL mongo >=0.9.0)

简介

这个类可以用于创建不同集合中对象间的轻量级的链接。

Motivation:如果我们需要引用其他集合中的文档。最简单的方法是在当前文档中创建一个字段。比如,有 "people" 集合和 "addresses" 集合,我们需要“关联”每个 person 和对应的 address ,可以:

Example #1 链接文档

<?php

$people 
$db->people;
$addresses $db->addresses;

$myAddress = array("line 1" => "123 Main Street"
    
"line 2" => null,
    
"city" => "Springfield",
    
"state" => "Vermont",
    
"country" => "USA");

// save the address 保存address文档
$addresses->insert($myAddress);

// save a person with a reference to the address 保存一个people,关联刚才的address
$me = array("name" => "Fred""address" => $myAddress['_id']);
$people->insert($me);

?>

然后,我们可以:把保存在 "people" 集合中的 MongoId 作为条件,查询 "address" 集合,来获取一个人的地址。

如果我们现在有更加一般性的的情况,我们不知道哪个集合(甚至数据库)中包含我们要引用的文档。 MongoDBRef 就是个好选择,它是一个更加通用的格式,所有的驱动和数据库都可以处理它。

如果每个“人”有一系列关联到其他多个集合的信息,例如爱好、运动、书籍等,我们可以用数个 MongoDBRef 对象来跟踪每一个 爱好 来自哪个集合:

Example #2 Creating MongoDBRef links

<?php

$people 
$db->selectCollection("people");

// model trains are in the "hobbies" collection
$trainRef MongoDBRef::create("hobbies"$modelTrains['_id']);
// soccer is in the "sports" collection
$soccerRef MongoDBRef::create("sports"$soccer['_id']);

// now we'll know what collections the items in the "likes" array came from when
// we retrieve this document
//  # 现在当我们读取这个文档的时候,就可以知道“likes”字段里的数组元素分别来自哪个集合了。
$people->insert(array("name" => "Fred""likes" => array($trainRef$soccerRef)));

?>

数据库引用可以被理解为超链接:它们指定了一个文档的唯一地址,但不会自动读取或者跟踪引用、链接。、

一个数据库引用仅仅是一个普通关联数组,不是 MongoDBRef 的实例,所以这个类与其他数据类型有些不同。这个类只包含静态方法,用来操作引用。 译注:上面两段的意思概括为 1.一个数据库引用与超链接相似,复制、删除、修改等操作不会影响原来的文档。 2.读取这个引用可以得知指向的文档的位置,但不能知道文档的内容,要手动解引用。 3.这个“引用”保存到Mongo的时候就是普通数组

类摘要

MongoDBRef {
/* 方法 */
public static create ( string $collection , mixed $id [, string $database ] ) : array
public static get ( MongoDB $db , array $ref ) : array
public static isRef ( mixed $ref ) : bool
}

参见

MongoDB 官方核心文档 » databases references.

Table of Contents