MongoDB数组中子文档聚合查询

问题描述 投票:0回答:1

我正在开发一个冥想应用程序的统计仪表板,但我在构建 MongoDB 查询来根据用户进度检索最常听的冥想时遇到了麻烦。相关集合是

users
meditations

users
集合中的用户文档如下所示:

{"_id": {"$oid": "627b519f73b2bd3375f5a7a5"}, "userProgress": {"meditationsPracticed": [{"timestamp": "11.5.2022, 9:03:34", "id": "5ef2ff0af1a23752be00651f"}, {"timestamp": "11.5.2022, 12:46:03", "id": "5eca520c10fe0480d350c9a4"}, /* more meditations */]}}

meditations
集合中的冥想文档如下所示:

{"_id": {"$oid": "5eca520c10fe0480d350c9ac"}, "name": "Sleep Well", "duration": {"$numberInt": "250"}}

我想创建一个查询,根据用户文档

id
字段中
meditationsPracticed
数组中的
userProgress
值检索最常听的冥想。

任何有关构建此 MongoDB 查询的帮助将不胜感激。谢谢!

我尝试使用 $unwind 和 $lookup 进行多次查询,但没有成功

javascript typescript database mongodb nosql
1个回答
0
投票

$unwind
首先位于
meditationsPracticed
级别。执行
$group
以按
meditations
id 获取计数。如果您有多个顶级冥想计数,请使用
$rank
计算
$setWindowFields
。然后,通过顶部冥想条目,您可以
$lookup
meditations
收藏中取回。

db.users.aggregate([
  {
    "$match": {
      "_id": {
        "$oid": "627b519f73b2bd3375f5a7a5"
      }
    }
  },
  {
    "$unwind": "$userProgress.meditationsPracticed"
  },
  {
    "$group": {
      "_id": {
        "$toObjectId": "$userProgress.meditationsPracticed.id"
      },
      "count": {
        "$sum": 1
      }
    }
  },
  {
    "$setWindowFields": {
      "partitionBy": "$_id",
      "sortBy": {
        "count": -1
      },
      "output": {
        "rank": {
          "$rank": {}
        }
      }
    }
  },
  {
    "$match": {
      "rank": 1
    }
  },
  {
    "$lookup": {
      "from": "meditations",
      "localField": "_id",
      "foreignField": "_id",
      "as": "meditationsLookup"
    }
  },
  {
    "$unwind": {
      "path": "$meditationsLookup",
      "preserveNullAndEmptyArrays": true
    }
  }
])

蒙戈游乐场

© www.soinside.com 2019 - 2024. All rights reserved.