简体   繁体   中英

FindOne() working to return records, but cannot use MongoDB aggregate query (sum records for ids) for Node.js

I have managed to get the connection open to my DB, and to return single records (which took a long time for me to work out how to do!):

MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;

MongoClient.connect('mongodb://localhost', function (err, client) {
  if (err) throw err;

  var db = client.db('payments');
        db.collection('general').findOne({ "Physician_Profile_ID" : {$eq: 346085}}, {projection:

            {'Physician_Profile_ID': 1,
            'Total_Amount_of_Payment_USDollars': 1,
            'Physician_First_Name': 1,
            'Physician_Last_Name': 1}

        }).then(function(doc) {
                if(!doc)
                    throw new Error('No records found!');
                    console.log('Here is the record: ')
                    console.log(doc);
          });
        });

The issue i'm having is that I want to have another call that is able to aggregate the records on the specified physician_profile_id. I want to perform this shell query:

db.general.aggregate
    ([{$match:{Physician_Profile_ID: 346085}},
    {$group:{_id: "$Physician_Profile_ID",
        total:{$sum: "$Total_Amount_of_Payment_USDollars"}}}])

How can I translate this into Node.js's dialect? The syntax you use for the Mongo shell isn't translating over

I have tried the following:

 var MongoClient = require('mongodb').MongoClient;
 var ObjectID = require('mongodb').ObjectID;
 //var o_id = new ObjectID("5b854c781c332b9558cece8d");

 MongoClient.connect('mongodb://localhost', function (err, client) {
   if (err) throw err;

   var db = client.db('payments');
        db.collection('general').aggregate({$match:{Physician_Profile_ID: 346085}},{$group:{_id: "$Physician_Profile_ID",
            total:{$sum: "$Total_Amount_of_Payment_USDollars"}}}).then(function(doc) {
                if(!doc)
                    throw new Error('No records found!');
                    console.log('Here is the bastard record: ')
                    console.log(doc);
          });
        });

It's throwing this error:

throw err;
      ^

TypeError: db.collection(...).aggregate(...).then is not a function
    at /Users/Badger/mongodb_connect.js:35:67
    at result (/Users/Badger/node_modules/mongodb/lib/utils.js:414:17)
    at executeCallback (/Users/Badger/node_modules/mongodb/lib/utils.js:406:9)
    at err (/Users/Badger/node_modules/mongodb/lib/operations/mongo_client_ops.js:286:5)
    at connectCallback (/Users/Badger/node_modules/mongodb/lib/operations/mongo_client_ops.js:241:5)
    at process.nextTick (/Users/Badger/node_modules/mongodb/lib/operations/mongo_client_ops.js:463:7)
    at _combinedTickCallback (internal/process/next_tick.js:132:7)
    at process._tickCallback (internal/process/next_tick.js:181:9)

Please can someone help me out, i've been looking for a few hours now and have searched on the site but aren't getting any luck. It's not making sense to me that the error is stating that aggregate isn't a function, when findOne() is. Unless aggregate has to be nested inside of Find(), but this isn't working for me either

Many thanks


Update:

Running this code:

 var MongoClient = require('mongodb').MongoClient;
 var ObjectID = require('mongodb').ObjectID;
 //var o_id = new ObjectID("5b854c781c332b9558cece8d");
 MongoClient.connect('mongodb://localhost', function (err, client) {
     if (err) throw err;
     var db = client.db('payments');
                db.collection('general').aggregate([{$match:{Physician_Profile_ID: 346085}},{$group:{_id: "$Physician_Profile_ID",
                        total:{$sum: "$Total_Amount_of_Payment_USDollars"}}}], function(err,doc) {
                                if(err)
                                        throw new Error('No records found!');
                                console.log('Here is the bastard record: ')
                                console.log(doc);
                    });
                });

Is returning output that is not expected:

AggregationCursor {
  pool: null,
  server: null,
  disconnectHandler: 
   Store {
     s: { storedOps: [], storeOptions: [Object], topology: [Object] },
     length: [Getter] },
  bson: BSON {},
  ns: 'payments.general',
  cmd: 
   { aggregate: 'general',
     pipeline: [ [Object], [Object] ],
     cursor: {} },
  options: 
   { readPreference: ReadPreference { mode: 'primary', tags: undefined },
     cursor: {},
     promiseLibrary: [Function: Promise],
     cursorFactory: { [Function: AggregationCursor] super_: [Object], INIT: 0, OPEN: 1, CLOSED: 2 },
     disconnectHandler: Store { s: [Object], length: [Getter] },
     topology: 
      Server {
        domain: null,
        _events: [Object],
        _eventsCount: 25,
        _maxListeners: Infinity,
        clientInfo: [Object],
        s: [Object] } },
  topology: 
   Server {
     domain: null,
     _events: 
      { serverOpening: [Function],
        serverDescriptionChanged: [Function],
        serverHeartbeatStarted: [Function],
        serverHeartbeatSucceeded: [Function],
        serverHeartbeatFailed: [Function],
        serverClosed: [Function],
        topologyOpening: [Function],
        topologyClosed: [Function],
        topologyDescriptionChanged: [Function],
        commandStarted: [Function],
        commandSucceeded: [Function],
        commandFailed: [Function],
        joined: [Function],
        left: [Function],
        ping: [Function],
        ha: [Function],
        authenticated: [Function],
        error: [Array],
        timeout: [Array],
        close: [Array],
        parseError: [Array],
        open: [Array],
        fullsetup: [Array],
        all: [Array],
        reconnect: [Array] },
     _eventsCount: 25,
     _maxListeners: Infinity,
     clientInfo: 
      { driver: [Object],
        os: [Object],
        platform: 'Node.js v8.12.0, LE' },
     s: 
      { coreTopology: [Object],
        sCapabilities: [Object],
        clonedOptions: [Object],
        reconnect: true,
        emitError: true,
        poolSize: 5,
        storeOptions: [Object],
        store: [Object],
        host: 'localhost',
        port: 27017,
        options: [Object],
        sessionPool: [Object],
        sessions: [],
        promiseLibrary: [Function: Promise] } },
  cursorState: 
   { cursorId: null,
     cmd: { aggregate: 'general', pipeline: [Array], cursor: {} },
     documents: [],
     cursorIndex: 0,
     dead: false,
     killed: false,
     init: false,
     notified: false,
     limit: 0,
     skip: 0,
     batchSize: 1000,
     currentLimit: 0,
     transforms: undefined,
     reconnect: true },
  logger: Logger { className: 'Cursor' },
  _readableState: 
   ReadableState {
     objectMode: true,
     highWaterMark: 16,
     buffer: BufferList { head: null, tail: null, length: 0 },
     length: 0,
     pipes: null,
     pipesCount: 0,
     flowing: null,
     ended: false,
     endEmitted: false,
     reading: false,
     sync: true,
     needReadable: false,
     emittedReadable: false,
     readableListening: false,
     resumeScheduled: false,
     destroyed: false,
     defaultEncoding: 'utf8',
     awaitDrain: 0,
     readingMore: false,
     decoder: null,
     encoding: null },
  readable: true,
  domain: null,
  _events: {},
  _eventsCount: 0,
  _maxListeners: undefined,
  s: 
   { maxTimeMS: null,
     state: 0,
     streamOptions: {},
     bson: BSON {},
     ns: 'payments.general',
     cmd: { aggregate: 'general', pipeline: [Array], cursor: {} },
     options: 
      { readPreference: [Object],
        cursor: {},
        promiseLibrary: [Function: Promise],
        cursorFactory: [Object],
        disconnectHandler: [Object],
        topology: [Object] },
     topology: 
      Server {
        domain: null,
        _events: [Object],
        _eventsCount: 25,
        _maxListeners: Infinity,
        clientInfo: [Object],
        s: [Object] },
     topologyOptions: 
      { host: 'localhost',
        port: 27017,
        disconnectHandler: [Object],
        cursorFactory: [Object],
        reconnect: true,
        emitError: true,
        size: 5,
        monitorCommands: false,
        socketOptions: {},
        socketTimeout: 360000,
        connectionTimeout: 30000,
        promiseLibrary: [Function: Promise],
        clientInfo: [Object],
        read_preference_tags: null,
        readPreference: [Object],
        dbName: 'admin',
        servers: [Array],
        server_options: [Object],
        db_options: [Object],
        rs_options: [Object],
        mongos_options: [Object],
        socketTimeoutMS: 360000,
        connectTimeoutMS: 30000,
        bson: BSON {} },
     promiseLibrary: [Function: Promise],
     session: undefined },
  sortValue: undefined }

You have to use db.collection('general').aggregate([{}])

when you do .aggregate it will return you a cursor, and with the cursor you can loop cursor.each but what you want to do most of the cases is to transform it into an array.

     MongoClient.connect('mongodb://localhost', function (err, client) {
       if (err) throw err;

       var db = client.db('payments');
            db.collection('general').aggregate([{$match:{Physician_Profile_ID: 346085}},{$group:{_id: "$Physician_Profile_ID",
                total:{$sum: "$Total_Amount_of_Payment_USDollars"}}}]).toArray(function(err,doc) {
                    if(err)
                        throw new Error('No records found!');
                    console.log('Here is the bastard record: ')
                    console.log(doc);
              });
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM