简体   繁体   中英

How to query a collection using count of a field in mongoDB using mongoose?

I have been trying to query the Document of posts. The query for the collection is as follows.

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

I am able to get the desired results but the issue is as soon as I add the date filter for the query it starts returning the empty array as a response

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 } }})

How do I solve this issue as well as have a null check for the collections that doesn't have "inappropriateReports" field?

Thanks in advance

Assuming you are checking in tribe-posts, try this:

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 } }})

I think passing date as a string will not work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM