16

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.)

1
  • Just call Contacts.aggregate(). The method is defined in the model and the syntax is just the same.
    – Neil Lunn
    Commented Dec 30, 2014 at 20:27

1 Answer 1

11

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) {
  // ...
});
1
  • Hi, Can you Also Explain How We Can Use .graphLookup() in Mongoose
    – Allex
    Commented Dec 8, 2022 at 10:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.