php - MongoDB 和 PHP 只获取匹配条形码的产品

标签 php mongodb search find database

我有这个 JSON,你可以在产品下看到我有每个产品的条形码我想做的只是获取与产品条形码匹配的信息

{
  "company": "village",
  "logo": "http:\/\/www.incard.com.au\/newsite\/template\/images\/movieticket\/4cinemas\/villagetop.png",
  "products": [
    {
      "barcode": "236690091",
      "name": "Weekday",
      "logo-URL": "http: \/\/www.incard.com.au\/newsite\/template\/images\/movieticket\/4cinemas\/ticketpic1.png",
      "price": "12.50",
      "discount": "1.50"
    },
    {
      "barcode": "236690092",
      "name": "Weekend",
      "logo-URL": "http: \/\/www.incard.com.au\/newsite\/template\/images\/movieticket\/4cinemas\/ticketpic1.png",
      "price": "13.50",
      "discount": "1.60"
    },
    {
      "barcode": "236690093",
      "name": "Gold Class",
      "logo-URL": "http: \/\/www.incard.com.au\/newsite\/template\/images\/movieticket\/4cinemas\/ticketpic1.png",
      "price": "13.50",
      "discount": "1.60"
    }
  ],
  "store_name": "movies"
}

例如,如果我点击 236690091,我只返回数据库 (MongoDB)

"barcode": "236690091",
      "name": "Weekday",
      "logo-URL": "http: \/\/www.incard.com.au\/newsite\/template\/images\/movieticket\/4cinemas\/ticketpic1.png",
      "price": "12.50",
      "discount": "1.50"

并非所有产品。

这是我试过的

public function getbarcode($barcode)
    {
        // select a collection (analogous to a relational database's table)
         $collection = $this->db->movies->products;

        // find everything in the collection
        $cursor = $collection->find(array("barcode" =>"{$barcode}"));

        $test = array();
            // iterate through the results
            while( $cursor->hasNext() ) {
                $test[] = ($cursor->getNext());
            }
        //Print Results 
        print json_encode($test);

    }

最佳答案

你不能这样做。 MongoDB 将始终返回完整文档,并且不允许您只返回要搜索的嵌套部分。我建议将产品拆分成自己的集合,然后将公司信息添加到每个产品。这也将规避 16MB 的文档限制,以防每家公司都有很多产品。

在不更改架构的情况下,以下代码应该可以工作:

public function getbarcode($barcode)
{
    $products = array();
    $collection = $this->db->movies->products;

    foreach( $collection->find( array( 'products.barcode' => $barcode ) ) as $item )
    {
        foreach( $item->products as $product )
        {
            if ( $product['barcode'] == $barcode )
            {
                $products[] = $item;
            }
        }
    }
    return $products;
}

关于php - MongoDB 和 PHP 只获取匹配条形码的产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9817478/

相关文章:

php - 如何跟踪我使用 PHP 的子类别?

php - 在 PHP 中计算 SHA1 类似于 C 中的 CC_SHA1_Update

php - 如果 php 每分钟更新 mysql 则排队

mongodb - React-Native 与 MongoDB 简单连接

mongodb - mongo objectid 'contains' 查询

php - 如何将可扩展的长轮询服务器与 PHP 集成?

MongoDB - 基于标签的自动完成搜索

android - 将上下文传递给语音搜索

C++在二维 map 中搜索占用的字段

algorithm - 使用 BST 搜索算法查找一般二叉树中可以搜索的节点数