1 | #!/usr/bin/env node
|
2 |
|
3 | var es = require('event-stream');
|
4 | var mongodb = require('mongodb');
|
5 | var sample = require('../');
|
6 | var toNS = require('mongodb-ns');
|
7 | var EJSON = require('mongodb-extjson');
|
8 | var pkg = require('../package.json');
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | var argv = require('yargs')
|
15 | .usage('Usage: $0 <uri> <ns> [options]')
|
16 | .demand(2)
|
17 | .option('n', {
|
18 | alias: 'size',
|
19 | default: 100,
|
20 | describe: 'The number of documents to sample.'
|
21 | })
|
22 | .option('f', {
|
23 | alias: 'fields',
|
24 | type: 'string',
|
25 | describe: 'field projection object',
|
26 | default: null
|
27 | })
|
28 | .option('q', {
|
29 | alias: 'query',
|
30 | type: 'string',
|
31 | describe: 'query filter',
|
32 | default: '{}'
|
33 | })
|
34 | .option('o', {
|
35 | alias: 'output',
|
36 | type: 'boolean',
|
37 | describe: 'Print the sampled documents to stdout.',
|
38 | default: true
|
39 | })
|
40 | .describe('debug', 'Enable debug messages.')
|
41 | .describe('version', 'Show version.')
|
42 | .alias('h', 'help')
|
43 | .describe('h', 'Show this screen.')
|
44 | .help('h')
|
45 | .argv;
|
46 |
|
47 | if (argv.debug) {
|
48 | process.env.DEBUG = '*';
|
49 | }
|
50 |
|
51 | var uri = argv._[0];
|
52 | if (!uri.startsWith('mongodb://')) {
|
53 | uri = 'mongodb://' + uri;
|
54 | }
|
55 | var sampleSize = parseInt(argv.size, 10);
|
56 |
|
57 | if (argv.version) {
|
58 | console.error(pkg.version);
|
59 | process.exit(1);
|
60 | }
|
61 |
|
62 | mongodb.connect(uri, function(err, conn) {
|
63 | if (err) {
|
64 | console.error('Failed to connect to MongoDB: ', err);
|
65 | process.exit(1);
|
66 | }
|
67 |
|
68 | var ns = toNS(argv._[1]);
|
69 | var db = conn.db(ns.database);
|
70 |
|
71 | var options = {
|
72 | size: sampleSize,
|
73 | query: JSON.parse(argv.query)
|
74 | };
|
75 |
|
76 | if (argv.fields !== null) {
|
77 | options.fields = JSON.parse(argv.fields);
|
78 | }
|
79 |
|
80 | sample(db, ns.collection, options)
|
81 | .pipe(es.map(function(data, cb) {
|
82 | if (data && argv.output) {
|
83 | console.log(EJSON.stringify(data, null, 2));
|
84 | }
|
85 | cb(null, data);
|
86 | }))
|
87 | .pipe(es.wait(function(sampleErr) {
|
88 | if (sampleErr) {
|
89 | console.error('Error sampling data:', sampleErr);
|
90 | process.exit(1);
|
91 | }
|
92 | process.exit(0);
|
93 | }));
|
94 | });
|