Sankar
Sankar

Reputation: 21

YII2 -MongoDB query for filtering nested array data

I'm facing problem with filtering data from monogo db embedded collection to YII2 frame work.If any one knows please help. I'm having Categories collection like below.

{
    "_id" : ObjectId("55cb2133b35be8b7de137462"),
    "category" : "Technology",
    "subCategory" : [
        {
            "_id" : 1,
            "sub_category_name" : "test1"

        },
        {
            "_id" : 2,
            "sub_category_name" : "test2"

        },
        {
            "_id" : 3,
            "sub_category_name" : "test3"

        },
        {
            "_id" : 4,
            "sub_category_name" : "test4"
        }
    ]
}

in that I want to fetch the data based on applying search condition on sub_Category.

expected result : I want to get value of ids 1 and 2 in sub category.

I have tried below method, but got all the sub categories.

Input : $id = [1,2];

 $query = new Query;
 $rows = $query->select([])
        ->from('category')
        ->where(array('_id' => '55c9caef8fae76a4a9d96c5a','subCategory._id' =>  $id));
  $rows = $query->all();

Anyone help on this.

Upvotes: 2

Views: 2708

Answers (1)

Blizz
Blizz

Reputation: 8408

If you want to select everything there is no need to actually call select. As for the rest, I think I notice 2 issues.

First I don't think Yii2 does auto MongoId conversion, so you'll see if you actually get the document back as a whole with just the _id selection (I don't think it will). Secondly, the name of the subdocument field seems wrong.

Here's what I think will help you further:

$query = (new Query)->from('category')
   ->where(array(
     '_id' => new \MongoId('55c9caef8fae76a4a9d96c5a'),
     'subCategory._id' => [1, 2]
));
$rows = $query->all();

MongoDB only matches if the type and the value match. This is why you probably need to convert your main _id to a MongoId and the subCategory._id need to be integers. In your example that should be fine, but PHP tends to end up with string valued variables after a couple of operations (especially if you obtained it via another database). So in that case an extra call to intval() might be needed for the subdocument query part.

Upvotes: 1

Related Questions