gpt4 book ai didi

2.4 中的 MongoDB Cross-db DBRef

转载 作者:可可西里 更新时间:2023-11-01 09:52:27 26 4
gpt4 key购买 nike

我在本地运行 MongoDB 2.4.6,测试时 MongoDB PECL 扩展是 1.4.3。

我目前正在开发一个应用程序,它有两个 MongoDB 数据库,一个名为 nc_main,包含一个名为 companies 的集合,另一个名为 nc_test带有一个名为 users 的集合。我正在尝试对其进行设置,以便 companies 文档可以引用 users 文档,但它似乎对我不起作用。当我查看公司文件时,我看到:

{
"_id" : ObjectId("xxxx"),
"maintainer" : DBRef("users", ObjectId("yyyy"))
}

但是 DBRef 是在 PHP 中设置的,使用:MongoDBRef::create('users', $user['id'], 'nc_test');

我可以运行以下查询,但它不会改变我查询文档时看到的内容:db.companies.update({ _id: ObjectId("xxxx") }, { $set: { maintainer : { "$ref": "users", "$id": ObjectId("yyyy"), "$db": "nc_test"} }}).

这导致的问题是,尝试通过引用加载 users 文档会导致文档未找到错误,因为它正在查找 nc_main 数据库而不是nc_test 就像我试图告诉它的那样。

最佳答案

请注意,shell 不支持 MongoDBRef 的 $db 字段名,这就是为什么它没有出现在那里的原因(仔细想想,它看起来像是 shell 中的一个错误,它甚至将数据转换为DBRef JavaScript 对象)。

此外,MongoDBRef 只是一个约定。它并不神奇,也不会做任何“自动获取”或“自动扩展”,它只是许多人用来“链接”同一集合中的文档的约定——在某些情况下,跨数据库。不过,并非所有 ODM(或相关驱动程序)都支持 $db 字段名。

话虽这么说,这是一个很好的约定 - 但我不太明白什么不适合你。你能告诉我你的“解析”代码是什么样子的吗? (例如,检索链接文档)。

例如,这是我为这个问题编写的测试用例,它似乎在 MongoDB 2.4.6 和 PHP Driver 1.4.3 上本地运行良好

<?php

$mc = new MongoClient;
$companies = $mc->selectCollection("nc_main", "companies");
$users = $mc->selectCollection("nc_test", "users");

/*
$companies->drop();
$users->drop();
*/



/* Create a user in nc_test.users */
$user = array(
"nick" => "bjori",
"title" => "Fixer",
);
$users->insert($user);

/* Create a reference to the newly created user */
$userref = MongoDBRef::create("users", $user["_id"], "nc_test");


/* Create a company in nc_main.copmanies */
$company = array(
"name" => "MongoDB",
"maintainer" => $userref,
);
$companies->insert($company);


/* Fetch the inserted company again, just to make sure the roundtrip didn't
* modify the MongoDBRef in any way */
$mongodb = $companies->findOne(array("_id" => $company["_id"]));
/* Get the reference.. */
$maintainer = $mongodb["maintainer"];

/* Backtrac the database to select from by passing it as the first argument */
$bjori = MongoDBRef::get($mc->selectDb($maintainer['$db']), $maintainer);
var_dump($bjori);
?>

结果:

array(3) {
["_id"]=>
object(MongoId)#14 (1) {
["$id"]=>
string(24) "528ab8c68c89fef7250041a7"
}
["nick"]=>
string(5) "bjori"
["title"]=>
string(5) "Fixer"
}

关于2.4 中的 MongoDB Cross-db DBRef,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19885998/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com