MongoDB, PHP and JavaScript
MongoDB, PHP and JavaScript
我在MongoDB 2.0.4和PHP 5.5*中有以下文档
{
"children" : [
{
"name" : "openGL::gl"
},
{
"name" : "openGL::interfaces"
},
{
"name" : "openGL::picking"
},
{
"name" : "openGL::objects"
}
],
"name" : "test"
}
使用php我想创建另一个集合有这个文档的副本。因为我不能使用php mongo::命令,我只是获取第一个集合的游标,并将此游标插入第二个集合:
$cursor = $collection->find();
foreach($cursor as $document){
$result->insert($document);
};
$collection是原来的,$result是新的。现在奇怪的是,有时这工作得很好,有时我收到以下内容:
{
"children" : {
"3" : {
"name" : "openGL::objects"
},
"0" : {
"name" : "openGL::gl"
},
"1" : {
"name" : "openGL::interfaces"
},
"2" : {
"name" : "openGL::picking"
}
},
"name" : "test"
}
这真的很糟糕,因为我试图把这些信息进入Javascript,因此第一个(原始)是一个数组,而第二个是一个对象的属性。有人知道为什么我得到这个和如何解决它吗?
所以这是我现在使用的解决方案!
$db->command(array(
"eval" => new MongoCode("function(){
db['".$toCopy."'].copyTo('".$newName."')
};"
)
));
您可以使用该集合的.copyTo()
方法在服务器上复制该集合:
db.collection.copyTo("new")
没有客户端传输,因为当前正在通过迭代完成。
如果出于某种原因你想让它成为你代码的一部分,那么有一个"runCommand"选项,它的语法更长。在PHP代码中,使用长版本的"eval":
$db->command(array(
"eval" => new MongoCode("function(){ " .
"db.collection.find().forEach(function(doc) { " .
"db.newcollection.insert(doc); " .
"}); " .
"};"
);
));
将在服务器上运行副本。请仔细阅读db.eval()
的文档和警告。除了这些之外,您还必须重新创建您想要使用的目标集合上的所有索引,这与您之前所做的基本相同。
您是否尝试过对游标进行如下排序:
$cursor = $collection->find();
$cursor = $cursor->sort(array('name_of_key_variable' => 1)); //sorts in ascending order
foreach($cursor as $doc) {
...
}
你也可以试试下面列出的更多的MongoCursor选项:http://www.php.net/manual/en/class.mongocursor.php在目录
相关文章:
- JavaScript and LiveView (TIBCO Live Datamart)
- Javascript and onMouseOver
- javascript and css firefox issue
- geolocation with javascript and ruby on rails
- Javascript and the DOM issues
- Javascript and Java Communication
- Javascript and Knockout
- Javascript and Css: Height does not change
- javascript and Internet Explorer 8
- Javascript and html, UI construction
- Javascript and Lightbox
- javascript and css styling
- JavaScript and URL parameters
- Javascript and singleton pattern
- Javascript and Ajax Calls
- OAuth, javascript and many URI's
- Javascript and AJAX post method
- javascript and web services WSDL
- javascript and webview in android
- Javascript & and | symbols