【问题标题】:Match with only one record after using $unwind on the record对记录使用 $unwind 后仅匹配一条记录
【发布时间】:2018-03-29 07:19:48
【问题描述】:

我有如下记录

[
  {
    _id : 1, nm : 1,
    usr:[
         {id : 1, ty : 'team'}, 
         {id : 2, em : 'a'}, 
         {id : 3, em : 'b'}
       ]
  },
  {
    _id : 2, nm : 2,
    usr:[
         {id : 2, em : 'a'}, 
         {id : 3, em : 'b'}
       ]
  },
  {
    _id : 3, nm : 3,
    usr:[
         {id : 1, ty : 'team'}, 
         {id : 3, em : 'b'}
       ]
  },
  {
    _id : 4, nm : 4,
    usr:[ 
         {id : 3, em : 'b'}
       ]
  }
]
  • 当使用userAndTeam = [1, 2] 查询时,我希望计数为3,即如果记录具有usr.id as 1 or 2,则获取这些记录。
  • 当使用userAndTeam4 = [1, 4] 查询时,我希望计数为2,即如果记录有usr.id as 1 or 4,则获取这些记录。

我尝试使用$unwind,这使得第一种情况的计数为4,因为$unwind为第一条记录创建了3条记录,下面的查询与其中2条记录匹配。

我尝试过的查询:

var userAndTeam = [1, 2] //User id and team id. Record should match one of the ids.
var userAndTeam4 = [1, 4]

[{
   $unwind: '$usr'
 },
 {
   $project:{
     'count-2' : {$cond: {
                if: {$in : ['$usr.id',userAndTeam]},
                then: 1,
                else: 0
            }},
      'count-4' : {$cond: {
                if: {$in : ['$usr.id',userAndTeam4]},
                then: 1,
                else: 0
            }}
   }   
 }

]

输出

预期用于 ID 为 2 - 'count-2' 的用户:3

得到 id 为 2 - 'count-2' 的用户:4

预期用于 ID 为 4 - 'count-4' 的用户:2

得到 id 为 4 - 'count-4' 的用户:2

有人可以指导我解决这个问题并获得预期的计数吗?

【问题讨论】:

  • 您可能需要查看“我的记录如下”部分,因为您不太清楚如何从提供的数据集。
  • @AlexBlex 请立即检查问题。我希望我的问题和要求现在更清楚了。

标签: mongodb aggregation-framework aggregation


【解决方案1】:

您可以尝试以下聚合:

db.col.aggregate([
    {
        $unwind: "$usr"
    },
    {
        $project:{
            "userId": "$usr.id",
            "count-2": {
                $cond: {
                    if: { $in: [ "$usr.id", userAndTeam ] },
                    then: 1,
                    else: 0
                }
            },
            "count-4": {
                $cond: {
                    if: { $in: [ "$usr.id", userAndTeam4] },
                    then: 1,
                    else: 0
                }
            }
        }
    },
    {
        $group: {
            _id: "$_id",
            "count-2": { $max: "$count-2" },
            "count-4": { $max: "$count-4" }
        }
    },
    {
        $group: {
            _id: null,
            "count-2": { $sum: "$count-2" },
            "count-4": { $sum: "$count-4" }
        }
    }
])

您的代码中缺少的是,您希望每个 _id 都有 01,因此您需要按 _id 分组,每个组的 $max 值为 @ 987654327@ 如果没有匹配 1 如果任何元素与您的数组匹配。

【讨论】:

    猜你喜欢
    • 2010-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-02
    • 1970-01-01
    相关资源
    最近更新 更多