Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Aggregate in mongoose

How do I define the following MongoDB aggregate query in mongoose:

db.contacts.aggregate([{$group: { "_id": { code: "$Code", name: "$Name" } } }])

The objective of the query is to pull a list of distinct codes and names.

My current model code is:

'use strict';

var mongoose = require('mongoose'),
    Schema = mongoose.Schema,
    ObjectId = Schema.ObjectId;

var fields = {
    Code: { type: String },
    Name: { type: String }
};

var contactSchema = new Schema(fields);

module.exports = mongoose.model('Contacts', contactSchema);

Router looks like this:

api.contacts = function (req, res) {
Contacts.find({ AgencyTranslation: /^BROADCASTING/ }, function(err, contacts) {
  if (err) {
    res.json(500, err);
  } else {    
    res.json({contacts: contacts});
  }
});

I tried various variations, also looked up the sample code at: mongoose API docs, but I cannot seem to get it working.

(Note: the above query does work in the MongoDB console.)

like image 989
Yossi Avatar asked Dec 30 '14 20:12

Yossi


People also ask

Can we use aggregate in mongoose?

Mongoose's aggregate() function is how you use MongoDB's aggregation framework with Mongoose. Mongoose's aggregate() is a thin wrapper, so any aggregation query that works in the MongoDB shell should work in Mongoose without any changes.

How does aggregate work in MongoDB?

In MongoDB, aggregation operations process the data records/documents and return computed results. It collects values from various documents and groups them together and then performs different types of operations on that grouped data like sum, average, minimum, maximum, etc to return a computed result.

What are aggregation pipelines with mongoose?

An aggregation pipeline consists of one or more stages that process documents: Each stage performs an operation on the input documents. For example, a stage can filter documents, group documents, and calculate values. The documents that are output from a stage are passed to the next stage.


1 Answers

Try this

Contacts.aggregate({$group: { "_id": { code: "$Code", name: "$Name" } } }, function(err, contacts) {
   ...
});

Or, with $match if you need this AgencyTranslation: /^BROADCASTING/ condition

Contacts.aggregate([
  { $match : { AgencyTranslation: /^BROADCASTING/ } },
  { $group: { "_id": { code: "$Code", name: "$Name" } } }
], function(err, contacts) {
  // ...
});
like image 55
Oleksandr T. Avatar answered Oct 19 '22 18:10

Oleksandr T.