如何在猫鼬中使用聚合

编程入门 行业动态 更新时间:2024-10-27 15:18:22
本文介绍了如何在猫鼬中使用聚合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

如何在猫鼬中定义以下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) { // ... });

更多推荐

如何在猫鼬中使用聚合

本文发布于:2023-11-22 07:09:01,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616442.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   猫鼬中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!