【问题标题】:How to use Aggregate in mongoose如何在猫鼬中使用聚合
【发布时间】:2015-02-27 00:08:40
【问题描述】:

如何在 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});
  }
});

我尝试了各种变体,还查看了示例代码:mongoose API docs,但我似乎无法让它工作。

(注意:上述查询在 MongoDB 控制台中确实有效。)

【问题讨论】:

  • 只需致电Contacts.aggregate()。方法在模型中定义,语法相同。

标签: node.js mongodb mongoose mongodb-query


【解决方案1】:

试试这个

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

或者,如果您需要这个AgencyTranslation: /^BROADCASTING/ 条件,请使用$match

Contacts.aggregate([
  { $match : { AgencyTranslation: /^BROADCASTING/ } },
  { $group: { "_id": { code: "$Code", name: "$Name" } } }
], function(err, contacts) {
  // ...
});

【讨论】:

    猜你喜欢
    • 2015-03-04
    • 2017-01-23
    • 1970-01-01
    • 2019-09-06
    • 1970-01-01
    • 2020-02-10
    • 2015-09-15
    • 2018-01-30
    • 2016-03-23
    相关资源
    最近更新 更多