这是一个关于在数组中添加一系列数据的最佳方法的问题,我必须匹配另一个元素.我正在尝试使用2.2聚合框架,我可以通过一个简单的组来实现这一点.
所以对于给定的一组文档,我试图获得这样的输出;
{
"result" : [
{
"_id" : null,
"numberOf": 2,
"Sales" : 468000,
"profit" : 246246,
}
],
"ok" : 1
}
Run Code Online (Sandbox Code Playgroud)
现在,我最初有一个文档列表,包含分配给命名属性的值,例如;
[
{
_id : 1,
finance: {
sales: 234000,
profit: 123123,
}
}
,
{
_id : 2,
finance: {
sales: 234000,
profit: 123123,
}
}
]
Run Code Online (Sandbox Code Playgroud)
这很容易加起来,但由于其他原因,结构不起作用.例如,可能有其他列,如"财务",我希望能够索引它们而不创建数千个索引,所以我需要转换为这样的结构;
[
{
_id : 1,
finance: [
{
"k": "sales",
"v": {
"description":"sales over the year",
v: 234000,
}
},
{
"k": "profit",
"v": {
"description":"money made …Run Code Online (Sandbox Code Playgroud) 在MySQL中,我只需要"SELECT sum(pts)FROM table"来获取表中pts列的总和.但是,我正在将此应用程序转换为MongoDB,并且无法找到一种直接的方法来获取我的集合中的公共密钥"type"的总和.我正在使用PHP,所以请提供PHP代码以使其工作.
这是我的数据:
{ "_id" : ObjectId("4f136dab5056f65b61000000"), "p_id" : "3", "g_id" : "1", "type" : "3" }
{ "_id" : ObjectId("4f136dad5056f65760000000"), "p_id" : "8", "g_id" : "1", "type" : "7" }
{ "_id" : ObjectId("4f136daf5056f65860000000"), "p_id" : "6", "g_id" : "1", "type" : "4" }
{ "_id" : ObjectId("4f136db15056f65460000000"), "p_id" : "27", "g_id" : "1", "type" : "2" }
Run Code Online (Sandbox Code Playgroud)
如何获得$ sum等于"type"键的总和?