简体   繁体   中英

How to fetch data from a collection named group in mongodb using PHP code

This is my PHP code for fetching data from a collection in mongodb:

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

The code works fine for the collection fields_current . But, I have a collection like this fields_current.node where node is the named group of the collection. How do I fetch data from the named group.

Edit:

After following PeterM's answer I am getting an empty MongoCursor object. This is my new code:

$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";
}

Some more details : I am using Drupal and node refers to the 'node' table, type is the 'node-type'. The collection name is fields_current.node and the record structure is this:

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',
  ),
)
$cursor = $collection->find(array('node' => 'group_name'));

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

Since its Drupal you do not have to specify the database name, just like when you write queries for MySql. And also there is a different function for getting a collection object.

// 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...
  ....
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM