【问题标题】:Retrieve only the sub document element in an object array in MongoDB collection in laravel在 laravel 的 MongoDB 集合中仅检索对象数组中的子文档元素
【发布时间】:2014-11-10 03:44:40
【问题描述】:

考虑以下集合,

 {
      "_id": ObjectId("545c535e75de3e630c8b4567"),

        "tables" : [
                {
                    "_id" : ObjectId("54584f5975de3e040fe97319"),
                    "title" : "001",
                },
                {
                    "_id" : ObjectId("54584fb175de3e1c0fe97319"),
                    "title" : "002",
                }
        ]
 }

我需要从其中 tables.title = "001" 的集合中检索数据。我使用了laravel框架。我尝试了以下代码,但没有正常工作。如果有人有解决此问题的想法,请帮助我。

DB::connection($this->connection)->collection($this->collection)->where('tables','elemMatch',array('title'=>"001"))->get();

DB::connection($this->connection)->collection($this->collection)->where('tables.title',"001")->get();

DB::connection($this->connection)->collection($this->collection)->where('tables.$.title',"001")->get();

【问题讨论】:

  • 我不了解 laravel 框架,但是 mongo 聚合查询可以解决您的问题。

标签: php mongodb laravel mongodb-query aggregation-framework


【解决方案1】:

对于“奇异”匹配,您应该只能使用投影:

$result = DB::collection('collection')->where(
    'tables.title', '001'
)->project(array( 'tables.$' => 1 ) )->get();

对于多个匹配项,您将需要访问“原始”驱动程序对象以“过滤”数组内容,因为您需要聚合框架来执行此操作。你可以这样做:

# Returns the original Mongo Result
$result = DB::collection('collection')->raw(function($collection)
{
    return $collection->aggregate(array(
        # Match the documents containing the matching elements first
        array(
            '$match' => array( 'tables.title' => '001' )
        ),

        # Unwind the array to "de-normalize"
        array( '$unwind' => '$tables' ),


        # Match again to "filter" the now "de-normalized" documents
        array(
            '$match' => array( 'tables.title' => '001' )
        ),

        # Construct back as an array
        array(
            '$group' => array(
                '_id' => '$_id',
                'tables' => array(
                    '$push' => '$tables'
                )
            )
        )   
    ));
});

【讨论】:

    【解决方案2】:

    以下聚合可能会解决您的问题,

    db.collectionName.aggregate({"$unwind":"$tables"},{"$project":{"title":"$tables.title","id":"$tables._id","_id":0}},{"$match":{"title":"001"}})
    

    这个返回标题和匹配标题的id

    【讨论】:

    • 谢谢。我尝试过这个。但是它在 laravel 中是如何实现的呢?
    猜你喜欢
    • 2018-04-13
    相关资源
    最近更新 更多