如何从拥有数千个条目的mongo文档中有效地检索字段?

时间:2015-12-15 10:56:29

标签: php mongodb

如何执行与此SQL查询相对应的mongo数据库查询操作

 array (
  '_id' => new MongoId("566fe2b5cdad8be9c4cad0cc"),
  'by' => 
  array (
    0 => new MongoInt32(218),
    1 => new MongoInt32(218),
  ),
  'msgid' => 
  array (
    0 => '1341',
    1 => '1341',
  ),
  'notification_count'▼ => new MongoInt32(2),
  'seen' => 
  array (
    0 => new MongoInt32(0),
    1 => new MongoInt32(0),
  ),
  'time' => 
  array (
    0 => new MongoInt32(1450173046),
    1 => new MongoInt32(1450174028),
  ),
  'type' => 
  array (
    0 => 'like',
    1 => 'like',
  ),
  'unseen_count' => new MongoInt32(2),
  'userid' => new MongoInt32(218),
)

我可以通过这样轻松地获取整个文档

$where=array('userid'=>(int)$param);

$cursor= $this->selectData(__COLLECTION_NOTIFICATIONS_BY_ID__, $columns, $where) ;




public function selectData($collectionName, $columns, $where = array(), $sort = array(), $limit = 0){

    try{
            //Create a db connection
            $db = $this->connection("mo"); 

            //Select colelction name
            $col = $db->$collectionName;

            if(!empty($sort) && !empty($limit))
            {
                //Select Query
                $documents =  $col->find($where, $columns)->sort($sort)->limit($limit);

            }else{

                //Select Query
                $documents =  $col->find($where, $columns);

            }

             //no error return 1;
             return array(1, $documents);

    }catch(Exception $e)
    {
        //Soemthing went wrong
        return array(-1, $e->getMessage());
    }


}

但我在一份文件中有超过1000条通知。

1。)我只想从这个特定文件中获得通知计数。

类似

SELECT notification_count FROM users WHERE userid=218

我试过

return $col->find($where,array('notification_count'=>1,'_id'=>0)); 

但显示

<br />
<b>Fatal error</b>:  Cannot use object of type MongoCursor as array in <b>/var/www/html/TradeTwits/app/models/Twits.php</b> on line <b>173</b><br />

2。)这是一种存储通知的正确方法,即在单个文档中存储数千条通知吗?

什么是更好的过程?

0 个答案:

没有答案