在 MongoDB 中使用乘法聚合 [英] Using multiply aggregation with MongoDB

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

问题描述

我有几个文件看起来像这样:

I have several documents that looks like this:

{
        "hostname" : "server1.example.com",
        "virtual" : true,
        "processors" : {
                "cores" : 1,
                "sockets" : 4
        }
}
{
        "hostname" : "server2.example.com",
        "virtual" : false,
        "processors" : {
                "cores" : 2,
                "sockets" : 2
        }
}

我正在尝试输出每个文档的主机名、虚拟内核数和内核总数.我不断收到让我难倒的语法错误.这是我的查询和语法错误.

I am trying to output the hostname, virtual and total number of cores for each document. I keep getting a syntax error that has me stumped. Here is my query and the syntax error.

c.aggregate( {
    $project: {
        hostname: 1,
        total-cores: {$multiply: ["$processors.sockets", "$processors.cores"]},
        virtual: 1,
        _id: 0
    }
});
Thu Apr 25 14:12:18 SyntaxError: missing : after property id (shell):1

从文档来看,这应该可行.我错过了什么?我正在运行 MongoDB 2.2.2.

Judging from the documentation, this should work. What am I missing? I am running MongoDB 2.2.2.

http://docs.mongodb.org/manual/reference/aggregation/project/

推荐答案

引用 total-cores 键,以便使用嵌入的连字符正确解析它:

Quote the total-cores key so that it's parsed correctly with the embedded hyphen:

c.aggregate({ 
    $project: { 
        hostname: 1, 
        "total-cores": {$multiply: ["$processors.sockets","$processors.cores"]}, 
        virtual: 1, 
        _id: 0  
    }
});

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

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