这是一个关于在数组中添加一系列数据的最佳方法的问题,我必须匹配另一个元素.我正在try 使用2.2聚合框架,我可以通过一个简单的组来实现这一点.
所以对于给定的一组文档,我试图得到这样的输出;
{
"result" : [
{
"_id" : null,
"numberOf": 2,
"Sales" : 468000,
"profit" : 246246,
}
],
"ok" : 1
}
现在,我最初有一个文档列表,包含指定给命名属性的值,例如;
[
{
_id : 1,
finance: {
sales: 234000,
profit: 123123,
}
}
,
{
_id : 2,
finance: {
sales: 234000,
profit: 123123,
}
}
]
这很容易加起来,但由于其他原因,这个 struct 不起作用.例如,可能还有其他类似"finance"的专栏,我希望能够在不创建数千个索引的情况下对它们进行索引,所以我需要转换成这样的 struct ;
[
{
_id : 1,
finance: [
{
"k": "sales",
"v": {
"description":"sales over the year",
v: 234000,
}
},
{
"k": "profit",
"v": {
"description":"money made from sales",
v: 123123,
}
}
]
}
,
{
_id : 2,
finance: [
{
"k": "sales",
"v": {
"description":"sales over the year",
v: 234000,
}
},
{
"k": "profit",
"v": {
"description": "money made from sales",
v: 123123,
}
}
]
}
]
我可以为金融编制索引.k,但我很难构建一个聚合查询,将与特定键匹配的所有数字相加.这就是我最初 Select 命名属性的原因,但这确实需要在有数千个"k"标签的情况下工作.
有人知道如何使用新框架为此构建聚合查询吗?我试过这个;
db.projects.aggregate([
{
$match: {
// QUERY
$and: [
// main query
{},
]
}
},
{
$group: {
_id: null,
"numberOf": { $sum: 1 },
"sales": { $sum: "$finance.v.v" },
"profit": { $sum: "$finance.v.v" },
}
},
])
但我得到了;
{
"errmsg" : "exception: can't convert from BSON type Array to double",
"code" : 16005,
"ok" : 0
}
**为了获得额外的荣誉,我还需要能够在MapReduce查询中实现这一点.