首页 > 解决方案 > 如何使用 mongoose 使用 mongoDB 中的字段计数来查询集合?

问题描述

我一直在尝试查询帖子文档。该集合的查询如下。

db.getCollection('posts').find({ isActive: true, inappropriateReports: { '$exists': true, '$gt': { '$size': 0 } }})

我能够获得所需的结果,但问题是,一旦我为查询添加日期过滤器,它就会开始返回空数组作为响应

db.getCollection('tribe-posts').find({ isActive: true,
  createdAt: {
    '$gte': '2021-06-01T00:00:00.000Z',
    '$lte': '2021-07-07T00:00:00.000Z'
  },
  inappropriateReports: { '$exists': true, '$gt': { '$size': 0 } }})

如何解决此问题以及对没有“inappropriateReports”字段的集合进行空检查?

提前致谢

标签: node.jsdatabasemongodbmongoosefiltering

解决方案


假设您正在检查部落帖子,请尝试以下操作:

db.getCollection('tribe-posts').find({ isActive: true,
  createdAt: {
    '$gte': new Date('2021-06-01T00:00:00.000Z'),
    '$lte': new Date('2021-07-07T00:00:00.000Z')
  },
  inappropriateReports: { '$exists': true, '$gt': { '$size': 0 } }})

我认为将日期作为字符串传递是行不通的。


推荐阅读