基于另一个集合中的条件聚合

时间:2021-06-24 12:47:38

标签: mongodb mongodb-query

我的数据库在 MongoDB 中。我有一个用户日志列表。一条日志如下:

{
    "userId" : ObjectId("5a176fa24d96415280e22cc8"),
    "date" : ISODate("2017-12-10T15:36:45.566Z"),
    ... ...
}

我有一个用户列表:

{
    "currentName" : "anonym"
    ... ...
},
{
    "currentName" : "Laurent Dupuis"
    ... ...
}

我有以下 shell 来按用户的日志数量排序和列出用户:

db.getCollection('logs').aggregate([
    { $group: { _id: "$userId", count: { $sum: 1 } } },
    { $lookup: { from:"users", localField:"_id", foreignField:"_id", as:"user" } }, 
    { $sort: { count: -1 } }
]);

但是,我不想考虑 currentNameanonym 的用户来构建该列表。有谁知道如何修改那个shell?

1 个答案:

答案 0 :(得分:1)

您可以使用specify-multiple-join-conditions-with--lookup

db.logs.aggregate([
  {
    $group: {
      _id: "$userId",
      count: { $sum: 1 }
    }
  },    
  {
    "$lookup": {
      "from": "users",
      "let": { uId: "$_id" },
      "pipeline": [
        {
          $match: {
            $expr: {
              $and: [
                { $not: { "$eq": [ "$currentName", "anonym" ] } },
                { "$eq": [ "$_id", "$$uId" ] }
              ]
            }
          }
        }
      ],
      "as": "user"
    }
  }
])

工作Mongo playground

相关问题