UNPKG

2.06 kBJavaScriptView Raw
1#!/usr/bin/env node
2
3var es = require('event-stream');
4var mongodb = require('mongodb');
5var sample = require('../');
6var toNS = require('mongodb-ns');
7var EJSON = require('mongodb-extjson');
8var pkg = require('../package.json');
9
10// var debug = require('debug')('mongodb-collection-sample:bin');
11
12/* eslint no-console: 0*/
13
14var 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
47if (argv.debug) {
48 process.env.DEBUG = '*';
49}
50
51var uri = argv._[0];
52if (!uri.startsWith('mongodb://')) {
53 uri = 'mongodb://' + uri;
54}
55var sampleSize = parseInt(argv.size, 10);
56
57if (argv.version) {
58 console.error(pkg.version);
59 process.exit(1);
60}
61
62mongodb.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});