2

这是我从 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指的是“节点”表,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',
  ),
)
4

2 回答 2

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

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

于 2012-07-12T16:50:16.010 回答
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...
  ....
}
于 2012-07-16T11:10:27.677 回答