Yos*_*ssi 9 mongoose mongodb node.js mongodb-query
如何在mongoose中定义以下MongoDB聚合查询:
db.contacts.aggregate([{$group: { "_id": { code: "$Code", name: "$Name" } } }])
Run Code Online (Sandbox Code Playgroud)
查询的目的是提取不同代码和名称的列表.
我目前的型号代码是:
'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);
Run Code Online (Sandbox Code Playgroud)
路由器看起来像这样:
api.contacts = function (req, res) {
Contacts.find({ AgencyTranslation: /^BROADCASTING/ }, function(err, contacts) {
if (err) {
res.json(500, err);
} else {
res.json({contacts: contacts});
}
});
Run Code Online (Sandbox Code Playgroud)
我尝试了各种变体,还查看了示例代码:mongoose API docs,但我似乎无法让它工作.
(注意:以上查询在MongoDB控制台中有效.)
试试这个
Contacts.aggregate({$group: { "_id": { code: "$Code", name: "$Name" } } }, function(err, contacts) {
...
});
Run Code Online (Sandbox Code Playgroud)
或者,$match如果你需要这个AgencyTranslation: /^BROADCASTING/条件
Contacts.aggregate([
{ $match : { AgencyTranslation: /^BROADCASTING/ } },
{ $group: { "_id": { code: "$Code", name: "$Name" } } }
], function(err, contacts) {
// ...
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18934 次 |
| 最近记录: |