Mongodb查询错误

时间:2016-09-07 11:24:19

标签: node.js mongodb aggregation-framework

我有一个名为Configuration的集合,配置有一个osType,我想计算所有osType和group by on company我正在使用这个解决方案

return Configuration.distinct("osType").then(function (name) {
  var types = name

  var groupObj = {"$group": {"_id": "$company.name"}},
    projectObj = {"$project": {"_id": 0, "Company": "$_id.company"}};

  var groupPipeline = types.reduce(function (obj, type) { // set the group pipeline object
    obj["$group"][type + "_count"] = {
      "$sum": {
        "$cond": [{"$eq": ["$type", type]}, 1, 0]
      }
    };
    return obj;
  }, groupObj);

  return Configuration.aggregate([groupPipeline]).then(function (result) {
    return {status: true, code: 200, message: "Configuration count", data: result}
  });

我收到此错误

"message": "exception: the group aggregate field name '8.1_count' cannot be used because $group's field names cannot contain '.'",

这是我的示例文档

{
  "_id" : ObjectId("57c97bd6ad85bac155aecafb"),
  "ITBConfigurationId" : 26921,
  "updatedAt" : ISODate("2016-09-02T13:17:10.066Z"),
  "createdAt" : ISODate("2016-09-02T13:17:10.066Z"),
  "id" : "23",
  "name" : "dav20-pc-126.dallas.dav20.thd",
  "type" : "Managed Workstation",
  "locationId" : null,
  "osType" : "7",
  "osInfo" : "Home Premium x64 Edition Service Pack 1 Build 7601",
  "company" : {
    "id" : 19300,
    "identifier" : "DAV20",
    "name" : "Davidson Stewart Morelock Ind Ins Group, LLC"
  },
  "__v" : 0
}

和不同的osType列表

[ '7',
 'Mac OS X',
 '8.1',
 'Vista',
 'XP',
 '2003',
 '2008',
 '2012',
 '8',
 'Linux',
 'Microsoft Windows Server 2012 R2 Datacenter x64',
 'Microsoft Windows Server 2012 R2 Standard x64',
 'Microsoft Windows 7 Professional  x64',
 '',
 '2000',
 'Microsoft Windows 7 Professional ',
 'Microsoft Windows 10 Pro x64',
 'Darwin',
 'Microsoft Windows Server 2012 Standard x64',
 'Microsoft Windows Server 2008 R2 Standard  x64',
 'Microsoft Windows XP Professional',
 'Microsoft Windows 8.1 Pro x64',
 'Microsoft® Windows Vista™ Home Premium  x64',
 'Microsoft Windows Server 2012 Datacenter x64',
 'Microsoft Windows Server 2003 for Small Business Server',
 'Microsoft® Windows Vista™ Business ',
 'Microsoft Windows 7 Home Premium  x64',
 'Microsoft Windows XP Home Edition',
 'Microsoft Windows 8 Pro x64',
 'Microsoft Windows 7 Home Premium ',
 'Microsoft Windows 8.1 x64',
 'Microsoft Windows 10 Home x64',
 'Microsoft Windows 8.1 Pro with Media Center x64',
 'Microsoft Windows 10 Pro' 
]

1 个答案:

答案 0 :(得分:0)

如错误所述,您无法在 '.' 管道字段中使用包含$group字符的字段名称。由于您是动态生成字段,因此在生成字段的代码中,使用下划线临时替换'.'字符的任何出现,并同样建议任何空格字符。

因此,动态返回管道对象的代码应为:

var groupObj = { "$group": { "_id": "$company.name" } };
var groupPipeline = types.reduce(function(obj, type) { 
    obj["$group"][type.replace(".", "_").replace(/\s+/g,"_") + "_count"] = {
        "$sum": {
            "$cond": [ { "$eq": [ "$osType", type ] }, 1, 0 ]
        }
    };
    return obj;
}, groupObj );