Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. Data Science
  3. Question
Data Science

How to use Aggregate in mongoose

Asked by Preetam Shetty Jul 15, 2021 1.2K views 1 answer
Share

About this question

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

Your answer

1 Answer

More Data Science discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest Data Science Blogs

Guides, tips and career advice on Data Science from JanBask experts.