如何在 mongoose 中定义以下 MongoDB 聚合查询:
db.contacts.aggregate([{$group: { "_id": { code: "$Code", name: "$Name" } } }])
查询的目的是获取不同代码和名称的列表。
我当前的模型代码是:
'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);
路由器看起来像这样:
api.contacts = function (req, res) {
Contacts.find({ AgencyTranslation: /^BROADCASTING/ }, function(err, contacts) {
if (err) {
res.json(500, err);
} else {
res.json({contacts: contacts});
}
});
我尝试了各种变体,还查找了示例代码:猫鼬 API 文档 http://mongoosejs.com/docs/api.html#aggregate_Aggregate,但我似乎无法让它工作。
(注意:上述查询在 MongoDB 控制台中确实有效。)