如何在猫鼬中使用聚合 [英] How to use Aggregate in mongoose

查看:84
本文介绍了如何在猫鼬中使用聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在猫鼬中定义以下MongoDB聚合查询:

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.

我当前的模型代码是:

'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文档 ,但似乎无法正常工作.

I tried various variations, also looked up the sample code at: mongoose API docs, but I cannot seem to get it working.

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

(Note: the above query does work in the MongoDB console.)

推荐答案

尝试一下

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

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

Or, with $match if you need this AgencyTranslation: /^BROADCASTING/ condition

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

这篇关于如何在猫鼬中使用聚合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆