Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Web Technology by (47.6k points)

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

2 Answers

0 votes
by (106k points)

To use aggregate in Mongoose you can do with $match if you need this AgencyTranslation: /^BROADCASTING/ condition

Contacts.aggregate([ 

{ $match : { AgencyTranslation: /^BROADCASTING/ } }, 

{ $group: { "_id": { code: "$Code", name: "$Name" } } } 

   ], function(err, contacts) { 

// ... 

});

0 votes
by (107k points)

Try this

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

   ...

});

Related questions

0 votes
2 answers
asked Oct 16, 2019 in Web Technology by Sammy (47.6k points)
+1 vote
2 answers
0 votes
2 answers
asked Oct 17, 2019 in Web Technology by Sammy (47.6k points)
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...