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
- Lost
listField in Projection: Your first$projectstage only keeps thenotifsfield, which drops the originallistarray from the pipeline. When the second$projecttries to reference$list, it no longer exists—this is the main reason you're getting null. - Invalid ObjectId: The
profileIdin your$matchstage has an invalid character (sinstead of a hexadecimal digit). ObjectIds require exactly 24 hex characters (0-9, a-f). - 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
$projectStage: We calculate the size oflistinline using$sizewithin the$condcheck, so we never lose access to the originallistarray. - Valid ObjectId: We fixed the typo in the
profileIdto 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
相关产品推荐
相关产品推荐

