如何在猫鼬中使用聚合

2024-05-27

如何在 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 控制台中确实有效。)


Try this

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

或者,与$match如果你需要这个AgencyTranslation: /^BROADCASTING/状况

Contacts.aggregate([
  { $match : { AgencyTranslation: /^BROADCASTING/ } },
  { $group: { "_id": { code: "$Code", name: "$Name" } } }
], function(err, contacts) {
  // ...
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在猫鼬中使用聚合 的相关文章

随机推荐