【问题标题】:Php MongoDB aggregation with match and sort order具有匹配和排序顺序的 PHP MongoDB 聚合
【发布时间】:2017-09-13 14:35:30
【问题描述】:

我在 Mongo Shell 中使用此查询来按“开始”字段的值顺序获取数组“事件”的元素

db.collection_name.aggregate(
{ $match: {
    _id : ObjectId("59941bec47582c1e92b93c9b")
}},
{ $unwind: '$events' },   
{ $sort: {
    'events.start': 1
}})

但我不明白如何在 php.ini 中做同样的事情。 我试图写这个没有结果:

$client = new MongoClient("mongodb://admin:$psw@localhost");
$collection = $client->db_name->collection_name;

$cursor = $collection->aggregate([
        ['$match' => ['_id' =>new MongoDB\BSON\ObjectID("59941bec47582c1e92b93c9b")]],
        ['$unwind' => '$events'],
        ['$sort' => ['events.start' => 1]]
]);

foreach($cursor as $document) {
    var_dump($document);
}

我也尝试过这种其他方式:

$manager = new MongoDB\Driver\Manager("mongodb://admin:$psw@localhost:27017");

$command = new MongoDB\Driver\Command([
    'aggregate' => 'collection_name',
    'pipeline' => [
        ['$match' => ['_id' =>new MongoDB\BSON\ObjectID("59941bec47582c1e92b93c9b")]],
        ['$unwind' => '$events'],
        ['$sort' => ['events.start' => 1]]
    ],
]);
$cursor = $manager->executeCommand('db_name', $command);

foreach($cursor as $key=>$document) {
    var_dump($document);
}

【问题讨论】:

  • 您的查询看起来不错。请考虑添加您期望查询返回的示例文档。通过运行简单的查找查询来验证您是否连接到具有正确权限的正确 mongo 服务器和数据库。
  • 好的,谢谢。使用第二个代码存在身份验证问题。我现在已经在连接 url 中添加了数据库名称。

标签: php mongodb aggregates


【解决方案1】:

我找到了解决方案。我改变了这一行:

$manager = new MongoDB\Driver\Manager("mongodb://admin:$psw@localhost:27017");

进入这个:

$manager = new MongoDB\Driver\Manager("mongodb://admin:$psw@localhost:27017/db_name");

这是一个身份验证问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 2020-11-18
    • 2015-10-09
    • 1970-01-01
    • 2015-03-29
    • 1970-01-01
    相关资源
    最近更新 更多