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

如何在MongoDB中查询包含空categories数组的所有文档

解决MongoDB查询数组长度为0的文档问题

你当前代码的问题在于使用了'categories.length' : 0的匹配条件,这会让MongoDB尝试查找名为categories.length的字段值为0的文档,而非categories数组长度为0的文档。

正确的写法是使用MongoDB的$size操作符,专门用于匹配指定长度的数组:

@Aggregation(pipeline = {
    "{ '$match': { 'categories': { '$size': 0 }}}"
})
List<CategoryProduct> findWithoutCategory();

如果需要确保categories字段本身存在(避免匹配到没有该字段的文档),可以补充$exists条件:

@Aggregation(pipeline = {
    "{ '$match': { 'categories': { '$exists': true, '$size': 0 }}}"
})
List<CategoryProduct> findWithoutCategory();

内容的提问来源于stack exchange,提问作者Rafael Souza

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 10:23:09