You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MongoDB数组统计与条件切片问题:现有查询返回null求解

Fixing Your MongoDB Aggregation Query

Let's break down why your query is returning null and how to fix it step by step:

Key Issues in Your Original Query

  1. Lost list Field in Projection: Your first $project stage only keeps the notifs field, which drops the original list array from the pipeline. When the second $project tries to reference $list, it no longer exists—this is the main reason you're getting null.
  2. Invalid ObjectId: The profileId in your $match stage has an invalid character (s instead of a hexadecimal digit). ObjectIds require exactly 24 hex characters (0-9, a-f).
  3. Redundant Slice for Full Array: Using $slice: ["$list", "$notifs"] to get all elements works, but it's simpler to just return the array directly.

Corrected Query

db.getCollection('post').aggregate([
  // Match the valid profileId from your sample document
  { $match: { profileId: ObjectId("5ad84c8c0e71892058b6a543") } },
  {
    $project: {
      notifications: {
        $cond: [
          // Check if the list has 10 or more elements
          { $gte: [{ $size: "$list" }, 10] },
          // Return first 10 elements if true
          { $slice: ["$list", 10] },
          // Return the entire list if false
          "$list"
        ]
      }
    }
  }
])

Explanation

  • Single $project Stage: We calculate the size of list inline using $size within the $cond check, so we never lose access to the original list array.
  • Valid ObjectId: We fixed the typo in the profileId to match the one from your sample document.
  • Simplified Logic: When the list is shorter than 10 elements, we directly return the full array instead of using $slice, making the query cleaner and more efficient.

Alternative (Include Total Notification Count)

If you also want to return the total number of notifications alongside the sliced list, you can add it to the projection:

db.getCollection('post').aggregate([
  { $match: { profileId: ObjectId("5ad84c8c0e71892058b6a543") } },
  {
    $project: {
      totalNotifications: { $size: "$list" },
      notifications: {
        $cond: [
          { $gte: [{ $size: "$list" }, 10] },
          { $slice: ["$list", 10] },
          "$list"
        ]
      }
    }
  }
])

This will give you both the total count of notifications and the appropriate sliced/full array.

内容的提问来源于stack exchange,提问作者Raju Adhikari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 06:37:04