MongoDB/Mongoose querying documents between certain dates?

I want it to obtain documents between certain dates, I know that I need to use the $and operator but right now I'm using Querymen, a middleware for MongoDB , I read the documentation but I couldn't find anything related to.

What I'm doing is this:

router.get('/',
  token({ required: true }),
  query({
    after: {
      type: Date,
      paths: ['fecha'],
      operator: '$gte'
    },
    before: {
      type: Date,
      paths: ['fecha'],
      operator: '$lte'
    }
  }),
  index)

So my question is how to use the $and operator

1 answer

  • answered 2018-08-09 01:12 shvetsovdm

    You don't have to use $and operator in your query. Instead of this:

    {
      $and: [
        { yourDateField: { $lte: '2018-08-09' } },
        { yourDateField: { $gte: '2018-08-03' } },
      ]
    }
    

    you can do:

    {
      yourDateField: {
        $lte: '2018-08-09',
        $gte: '2018-08-03'
      }
    }
    

    So you can use this schema for querymen:

    const querySchema = {
      after: {
        type: Date,
        paths: ['yourDateField'],
        operator: '$gte'
      },
      before: {
        type: Date,
        paths: ['yourDateField'],
        operator: '$lte'
      }
    };
    

    Full example may be looking like this:

    const querymen = require('querymen');
    const app = require('express')();
    
    const querySchema = {
      after: {
        type: Date,
        paths: ['yourDateField'],
        operator: '$gte'
      },
      before: {
        type: Date,
        paths: ['yourDateField'],
        operator: '$lte'
      }
    };
    
    app.get('/', querymen.middleware(querySchema), (req, res) => {
      const { querymen: { query } } = req;
      res.json({ ok: true, query });
    });
    
    app.listen(8000, () => console.log('Up and running on http://localhost:8000'));
    

    If you still in doubt why not use $and operator look at this answer.