使用javascript在mongodb终端中创建查询

时间:2022-03-31 21:11:53

Basically, I have a database in Mongodb and I want to be able to search for specific things in it. I want to have a javaScript file called search.js which takes in these parameters on the command line/terminal

基本上,我在Mongodb中有一个数据库,我希望能够在其中搜索特定的东西。我想要一个名为search.js的javaScript文件,它在命令行/终端上接收这些参数

node search.js --output=file.txt --maxItems=2 

This should run this search in the database:

这应该在数据库中运行此搜索:

db.DatabaseName.find().limit(2)

and print the results of that to the specified file beside the output parameter. I should note that if --output isn't specified it should just default to the terminal or --maxItems isn't specified then it should print all items in the result.

并将其结果打印到输出参数旁边的指定文件中。我应该注意,如果未指定--output,它应该默认为终端或未指定--maxItems然后它应该打印结果中的所有项目。

I can get most of the functionality working individually but I'm having trouble putting it into a JavaScript file and taking arguments from the command line. Can anyone lead me in the right direction?

我可以将大部分功能单独工作,但是我无法将其放入JavaScript文件并从命令行获取参数。谁能引导我朝着正确的方向前进?

1 个解决方案

#1


3  

I somehow get the feeling here that what you are actually asking is indeed a lot more broad than what you are letting on in the question. And it really is since you seem to be asking for a "nodejs" version of "mongoexport". That really is way to broad an ask, but we can at least cover the basics.

我在某种程度上感觉到你实际上问的问题确实比你在问题中提出的要广泛得多。这真的是因为你似乎要求“mongoexport”的“nodejs”版本。这确实是广泛问的方式,但我们至少可以涵盖基础知识。

In addition to the sort of "options" you want specified, you also want a good sensible number of defaults in addition to "required" input, which should primarily be the collection name as there would be no point to hard-coding a default for that value.

除了你想要指定的那种“选项”之外,除了“必需”输入之外,你还需要一个很好的合理数量的默认值,它应该主要是集合名称,因为没有必要对默认值进行硬编码。那个价值。

That options processing really should be something beyond just the rudimentary argument passing. node-getopt is an example that implements things in a reasonable industry standard way.

选项处理确实应该超越仅仅是基本的论证。 node-getopt是一个以合理的行业标准方式实现事物的示例。

So this listing covers the basics of how to handle things. Adding other functionality is up to you:

所以这个清单涵盖了如何处理事情的基础知识。添加其他功能取决于您:

var fs = require('fs'),
    MongoClient = require('mongodb').MongoClient,
    Getopt = require('node-getopt');

var getopt = new Getopt([
  [ 'o',  'output-file=ARG',    'Output file or STDOUT' ],
  [ 'm',  'maxItems=ARG',       'Maximum output items' ],
  [ '',   'host=ARG',           'optional host' ],
  [ '',   'port=ARG',           'optional port' ],
  [ 'd',  'database=ARG',       'optional database' ],
  [ 'h',  'help',               'display this help' ],
  [ 'v',  'version',            'show version' ]
]).bindHelp();

var opt = getopt.parse(process.argv.slice(2));

if ( opt.argv[0] == undefined ) {
  console.log("collection name must be included");
  process.exit(-1);
}

var options = {
  "host": opt.options.host || 'localhost',
  "port": opt.options.port || 27017,
  "database": opt.options.database || 'test',
  "maxItems": 0,
};

try {
  options.maxItems = parseInt(opt.options.maxItems || options.maxItems);
  if ( isNaN(options.maxItems) )
    throw new Error("maxItems needs to be numeric");
} catch(e) {
  console.log(e);
  process.exit();
}

console.log( options );

MongoClient.connect(
  'mongodb://' +   options.host + ':' + options.port
  + '/' + options.database,
  function(err,db) {
    if (err) throw err;

    db.collection(opt.argv[0],function(err,collection) {
      if (err) throw err;

      var stream = collection.find().limit(options.maxItems).stream();

      stream.on('data',function(data) {
        stream.pause();
        if ( !options.hasOwnProperty('writer') ) {
          try {
            options.writer = opt.options.hasOwnProperty("output-file") ?
              fs.openSync( opt.options["output-file"], 'w' )
              : process.stdout.fd;
          } catch(e) {
            throw e;
         }
        }

        var block = JSON.stringify(data) + "\n";
        fs.writeSync( options.writer, block );
        stream.resume();
      });

      stream.on('end',function() {
        db.close();
      });

      stream.on('error',function(err) {
        throw err;
      });

    });
  }
);

So if I just called that sample.js then I could run for example like:

所以,如果我只是调用那个sample.js那么我可以运行例如:

node sample.js messages --maxItems 10 --output-file output.json

#1


3  

I somehow get the feeling here that what you are actually asking is indeed a lot more broad than what you are letting on in the question. And it really is since you seem to be asking for a "nodejs" version of "mongoexport". That really is way to broad an ask, but we can at least cover the basics.

我在某种程度上感觉到你实际上问的问题确实比你在问题中提出的要广泛得多。这真的是因为你似乎要求“mongoexport”的“nodejs”版本。这确实是广泛问的方式,但我们至少可以涵盖基础知识。

In addition to the sort of "options" you want specified, you also want a good sensible number of defaults in addition to "required" input, which should primarily be the collection name as there would be no point to hard-coding a default for that value.

除了你想要指定的那种“选项”之外,除了“必需”输入之外,你还需要一个很好的合理数量的默认值,它应该主要是集合名称,因为没有必要对默认值进行硬编码。那个价值。

That options processing really should be something beyond just the rudimentary argument passing. node-getopt is an example that implements things in a reasonable industry standard way.

选项处理确实应该超越仅仅是基本的论证。 node-getopt是一个以合理的行业标准方式实现事物的示例。

So this listing covers the basics of how to handle things. Adding other functionality is up to you:

所以这个清单涵盖了如何处理事情的基础知识。添加其他功能取决于您:

var fs = require('fs'),
    MongoClient = require('mongodb').MongoClient,
    Getopt = require('node-getopt');

var getopt = new Getopt([
  [ 'o',  'output-file=ARG',    'Output file or STDOUT' ],
  [ 'm',  'maxItems=ARG',       'Maximum output items' ],
  [ '',   'host=ARG',           'optional host' ],
  [ '',   'port=ARG',           'optional port' ],
  [ 'd',  'database=ARG',       'optional database' ],
  [ 'h',  'help',               'display this help' ],
  [ 'v',  'version',            'show version' ]
]).bindHelp();

var opt = getopt.parse(process.argv.slice(2));

if ( opt.argv[0] == undefined ) {
  console.log("collection name must be included");
  process.exit(-1);
}

var options = {
  "host": opt.options.host || 'localhost',
  "port": opt.options.port || 27017,
  "database": opt.options.database || 'test',
  "maxItems": 0,
};

try {
  options.maxItems = parseInt(opt.options.maxItems || options.maxItems);
  if ( isNaN(options.maxItems) )
    throw new Error("maxItems needs to be numeric");
} catch(e) {
  console.log(e);
  process.exit();
}

console.log( options );

MongoClient.connect(
  'mongodb://' +   options.host + ':' + options.port
  + '/' + options.database,
  function(err,db) {
    if (err) throw err;

    db.collection(opt.argv[0],function(err,collection) {
      if (err) throw err;

      var stream = collection.find().limit(options.maxItems).stream();

      stream.on('data',function(data) {
        stream.pause();
        if ( !options.hasOwnProperty('writer') ) {
          try {
            options.writer = opt.options.hasOwnProperty("output-file") ?
              fs.openSync( opt.options["output-file"], 'w' )
              : process.stdout.fd;
          } catch(e) {
            throw e;
         }
        }

        var block = JSON.stringify(data) + "\n";
        fs.writeSync( options.writer, block );
        stream.resume();
      });

      stream.on('end',function() {
        db.close();
      });

      stream.on('error',function(err) {
        throw err;
      });

    });
  }
);

So if I just called that sample.js then I could run for example like:

所以,如果我只是调用那个sample.js那么我可以运行例如:

node sample.js messages --maxItems 10 --output-file output.json