如何使用PHP代码从mongodb中的名为group的集合中获取数据

时间:2012-07-12 16:22:19

标签: php mongodb drupal-7

这是我用于从mongodb中的集合中获取数据的PHP代码:

$m = new Mongo('localhost');
$m->connect();
$db = $m->mydb;
$collection = $db->fields_current;
$cursor = $collection->find();
foreach ($cursor as $obj) {
    echo $obj["title"] . "\n";
}

代码适用于集合fields_current。但是,我有一个像fields_current.node这样的集合,其中node是集合的命名组。如何从命名组中获取数据。

修改

按照PeterM的回答后,我得到一个空的MongoCursor对象。这是我的新代码:

$m = new Mongo('localhost');
$m->connect();
$db = $m->mydb;
$collection = $db->fields_current;
$query = array(array('group_name' => 'node', 'type' => 'content-type'), array('title' => 1)); // SELECT title FROM fields_current WHERE group_name = 'node' AND type = 'content-type'
$cursor = $collection->find($query);
foreach ($cursor as $obj) {
    echo $obj["title"] . "\n";
}

更多细节:我使用Drupal,node引用'node'表,type是'node-type'。集合名称为fields_current.node,记录结构为:

array (
  '_id' => new MongoInt32(37),
  '_type' => 'node',
  '_bundle' => 'content-type',
  '_revision_id' => new MongoInt32(37),
  'nid' => new MongoInt32(37),
  'vid' => new MongoInt32(37),
  'type' => 'content-type',
  'language' => 'und',
  'title' => 'title',
  'uid' => new MongoInt32(1),
  'status' => new MongoInt32(1),
  'created' => new MongoInt32(1342065549),
  'changed' => new MongoInt32(1342065549),
  'comment' => new MongoInt32(1),
  'promote' => new MongoInt32(0),
  'sticky' => new MongoInt32(0),
  'tnid' => new MongoInt32(0),
  'translate' => new MongoInt32(0),
  'field_cutom_field' => 
  array (
    'value' => 'foobar',
  ),
)

2 个答案:

答案 0 :(得分:2)

$cursor = $collection->find(array('node' => 'group_name'));

有关更多示例,请参阅http://www.php.net/manual/en/mongo.sqltomongo.php

答案 1 :(得分:2)

因为它的Drupal你不必指定数据库名称,就像你为MySql编写查询一样。并且还有一个不同的函数来获取集合对象。

// Suppose you have a collection called 'collection_name', then you can get its object using this code.
$collection = mongodb_collection('collection_name');

// Suppose you have a collection called 'collection_name.group', where 'group' is the named group of this collection, then you can get its object using this code.
$collection = mongodb_collection('collection_name', 'group');

// Rest of the operations will be same.
$cursor = $collection->find(array('type' => 'content-type'));
foreach ($cursor as $obj) {
  ....
  // Do your work...
  ....
}