MongoDB聚合:多重分组+元素数组。

3
文档的结构看起来像这样:
"_id" : ObjectId("581496e8564627c098e41755"),
"startdate": somedate,
"enddate": somedate,
"userId" : 1,
"activity" : "activity1",
"measures" : [ 
    {
        "M1" : 99,
        "M2" : 103,
        "M3" : 118,
        "M4" : 4
    }, 
    {
        "M1" : 136,
        "M2" : 89,
        "M3" : 108,
        "M4" : 6
    }, 

有50个用户,8种活动,每种活动大约有100个措施。一个用户可以在其他日期进行相同的活动,并使用其他措施。

我在数据库中有大约3000个文档:每个用户每个活动一个文档,包括措施。

我想要获取每个用户每个活动的所有措施。

我有以下代码:

`db.armband.aggregate([
  {$match: { "measures.M1": { $gt: 1 } } },
  {$project: { _id: 0, userId: 1, activity:1, measures:1 } },
  {$sort: {userId:1, activity:1} },
  {$out: "actPerUser"}
  ])
` 

问题出在我根据顺序获得每个活动的1个文档并附带措施。但是,我获得了:

  • 1个具有userid1、activity1和措施100的文档
  • 1个具有userid1、activity1和措施100的文档
  • 1个具有userid2、activity1和措施100的文档

我想要一个文档:userid1、activity1和措施(该活动所有措施 - 在上面的示例中为200)。

然后我尝试过:

`db.armband.aggregate(
   [
     {
      $group:
     {
      _id: { userId: "$userId" },
       actMes: { $push:  { activity:"$activity", measures:   "$measures"     }     }
     }
   },
   {$project: { _id: 0, userId: "$_id.userId", actMes:1 } },
   {$sort: { userId:1}},     
 ]

这为我提供了每个用户的1个文档,其中列举了不同的活动和措施(但活动仍然是重复的)。

然后我尝试解开措施:

  `db.armband.aggregate(
    [
     {$unwind: '$measures'},
     {$group: {
     _id: { userId: "$userId" },
    activity: { $addToSet: "$activity" },
    measures: {$addToSet: "$measures"}
         }
       },
     { $sort: {userId:1}}
    ])
  `

这给我每个用户一个文档,其中包含8项活动和约5900的测量值。

所以我有点迷失,如何实现我想要的?是否可能,即每个用户一个文档,一个活动,该活动的所有测量值?

1个回答

2
您可以使用:
  • 1 $unwind 来移除数组
  • 1 $group 通过活动/用户ID进行分组,然后将度量值 $push 到新创建的数组中

查询如下:

db.armband.aggregate([{
    "$unwind": "$measures"
}, {
    $group: {
        _id: {
            userId: "$userId",
            activity: "$activity"
        },
        measures: { $push: "$measures" }
    }
}])

这将得到类似于以下内容:
{ "_id" : { "userId" : 2, "activity" : "activity1" }, "measures" : [ { "M1" : 99, "M2" : 103, "M3" : 118, "M4" : 4 }, { "M1" : 136, "M2" : 89, "M3" : 108, "M4" : 6 } ] }
{ "_id" : { "userId" : 2, "activity" : "activity2" }, "measures" : [ { "M1" : 99, "M2" : 103, "M3" : 118, "M4" : 4 }, { "M1" : 136, "M2" : 89, "M3" : 108, "M4" : 6 } ] }
{ "_id" : { "userId" : 1, "activity" : "activity1" }, "measures" : [ { "M1" : 99, "M2" : 103, "M3" : 118, "M4" : 4 }, { "M1" : 136, "M2" : 89, "M3" : 108, "M4" : 6 }, { "M1" : 99, "M2" : 103, "M3" : 118, "M4" : 4 }, { "M1" : 136, "M2" : 89, "M3" : 108, "M4" : 6 } ] }

谢谢,就这些了。一开始我以为执行代码时每个用户只能获取50个文档来完成一个活动。但这其实是Robomongo的问题。当我将它写入新的集合($out)时,我确实获得了所有文档,每个用户每个活动都有一个文档,并包含该活动的所有测量值。再次感谢! - alve

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接