简体   繁体   中英

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

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 .

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