node.js 如何在猫鼬中使用聚合
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27712022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use Aggregate in mongoose
提问by Yossi
How do I define the following MongoDB aggregate query in mongoose:
如何在 mongoose 中定义以下 MongoDB 聚合查询:
db.contacts.aggregate([{$group: { "_id": { code: "$Code", name: "$Name" } } }])
The objective of the query is to pull a list of distinct codes and names.
查询的目的是提取不同代码和名称的列表。
My current model code is:
我目前的型号代码是:
'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);
Router looks like this:
路由器长这样:
api.contacts = function (req, res) {
Contacts.find({ AgencyTranslation: /^BROADCASTING/ }, function(err, contacts) {
if (err) {
res.json(500, err);
} else {
res.json({contacts: contacts});
}
});
I tried various variations, also looked up the sample code at: mongoose API docs, but I cannot seem to get it working.
我尝试了各种变体,还查找了示例代码:mongoose API docs,但我似乎无法让它工作。
(Note: the above query does work in the MongoDB console.)
(注意:上面的查询在 MongoDB 控制台中确实有效。)
采纳答案by Alexander T.
Try this
尝试这个
Contacts.aggregate({$group: { "_id": { code: "$Code", name: "$Name" } } }, function(err, contacts) {
...
});
Or, with $matchif you need this AgencyTranslation: /^BROADCASTING/condition
或者,$match如果你需要这个AgencyTranslation: /^BROADCASTING/条件
Contacts.aggregate([
{ $match : { AgencyTranslation: /^BROADCASTING/ } },
{ $group: { "_id": { code: "$Code", name: "$Name" } } }
], function(err, contacts) {
// ...
});

