如何在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
相关产品推荐
相关产品推荐

