将聚合方法与PHP中的新MongoDB驱动程序类一起使用 [英] Use aggregate method with the new MongoDB driver classes in PHP

查看:87
本文介绍了将聚合方法与PHP中的新MongoDB驱动程序类一起使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是mongo的新人.

I am new with mongo.

我尝试获取文档的子文档,这是我的文档:

I try to get a subDocument of a document, here is my document :

{
    "_id" : ObjectId("5900ab35c720b210c000032c"),
    "name" : "B 1",
    "providers" : [ 
        {
            "id" : ObjectId("59030550c720b211dc005e9e"),
            "name" : "F 1"
        }, 
        {
            "id" : ObjectId("59030577c720b211dc005e9f"),
            "name" : "F 2"
        }
    ]
}

我想得到这个子文档:

{
    "id" : ObjectId("59030577c720b211dc005e9f"),
    "name" : "F 2"
}

我认为我需要使用这些类: http://php.net/manual/zh-CN/mongocollection.aggregate.php ,但我没有设法将其与该类的经理实例一起使用:

I think I need to use these class : http://php.net/manual/en/mongocollection.aggregate.php but I didn't manage to use it with my manager instance of the class : http://php.net/manual/en/class.mongodb-driver-manager.php.

PHP手册未显示如何与新驱动程序一起使用.

The PHP Manual do not show how to use it with the new Driver.

有人可以帮助我吗?

谢谢你,美好的一天!

推荐答案

您不必为任务使用聚合.

You don't have to use aggregation for the task.

您可以使用常规查询来选择嵌入式数组中的第一个匹配子文档.

You can use regular queries for selecting the first matching sub document in the embedded arrays.

您可以通过两种方式进行处理.

You can approach it in a couple of ways.

$ Positional 投影

$filter = ['_id' => new MongoDB\BSON\ObjectID("5900ab35c720b210c000032c"), 'providers.id' => new MongoDB\BSON\ObjectID("59030577c720b211dc005e9f") ];

$options = ['projection' => ['_id' => 0, 'providers.$' => 1],];

$ elemMatch 投影

$filter = ['_id' => new MongoDB\BSON\ObjectID("5900ab35c720b210c000032c")];

$options = [
        'projection' => ['_id' => 0, 'providers' => ['$elemMatch'=> ['id' => new MongoDB\BSON\ObjectID("59030577c720b211dc005e9f")]]],
    ];

您将使用executeQuery运行常规查询.

You'll use the executeQuery to run regular queries.

$query = new \MongoDB\Driver\Query($filter, $options);

$cursor = $manager->executeQuery(dbName.collectionName, $query); 

这篇关于将聚合方法与PHP中的新MongoDB驱动程序类一起使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆