使用Perl的Mongo DB JavaScript

时间:2017-08-17 15:16:57

标签: mongodb perl

我们可以直接从Perl运行Java Script来从MongoDB获取数据吗?

假设我当前的JS文件是: -

DBQuery.shellBatchSize = 194127180 ; 
permissibleCars = 
 ["C:93124617:54413209463","C:93124633:54413165206","C:93124634:54413165224"]

db.getCollection('Test').aggregate([
{$match:
  {         "methods.name": "Download",
            "methods.status": "ACTIVE",       
            container: {"$in": permissibleCars},
            entitlementClass : "Download"

    } },
{"$group" : {_id:"$container", count:{$sum:9}}}
],
{ allowDiskUse: true}
);

通常当我们运行shell / bash时,我们运行它: -

mongo hostname:portnumber/db_name - user_name -p password < filename.js > output_file.txt

但我不知道如何使用perl运行它。

有人可以帮我吗?我通过文件阅读没有看到任何与JS有关的东西。

此致

2 个答案:

答案 0 :(得分:1)

您可以使用Perl的system()函数来运行该命令。但是,当a Perl module for accessing Mongo databases出现时,这似乎是一种非常棒的巴洛克方式。

答案 1 :(得分:1)

使用Perl驱动程序,您可以通过aggregate method

执行此操作

它看起来像这样:

use strict;
use warnings;
use MongoDB;

my $mc   = MongoDB->connect('mongodb://user:pass@host:port/dbname');
my $coll = $mc->ns("dbname.Test");

my @permissibleCars =
  ( "C:93124617:54413209463", "C:93124633:54413165206", "C:93124634:54413165224" );

my @pipeline = (
    {
        '$match' => {
            "methods.name"     => "Download",
            "methods.status"   => "ACTIVE",
            "container"        => { '$in' => \@permissibleCars },
            "entitlementClass" => "Download"

        }
    },
    { '$group' => { _id => '$container', count => { '$sum' => 9 } } }
);

my $res = $coll->aggregate( \@pipeline, { allowDiskUse => 1 } );

然后使用MongoDB::QueryResult中的方法从$res迭代器中获取结果。

注意不要在要发送到数据库的$ -prefixed字段中使用双引号!

已添加进行验证

 use Data::Printer;
 while (my $row = $res->next) {print $row->{'container'}}
相关问题