仅检索laravel中MongoDB集合中对象数组中的子文档元素

时间:2014-11-10 03:44:41

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

考虑以下集合,

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

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

我需要从这个集合中检索table.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();

2 个答案:

答案 0 :(得分:6)

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

$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'
                )
            )
        )   
    ));
});

答案 1 :(得分:2)

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

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

此回复标题和匹配标题的ID