简体   繁体   English

MongoDB /猫鼬在某些日期之间查询文档?

[英]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. 我希望它在某些日期之间获取文档,我知道我需要使用$ and运算符,但是现在我正在使用Querymen ,它是MongoDB的中间件,我阅读了文档,但找不到任何相关的内容。

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 所以我的问题是如何使用$ and运算符

You don't have to use $and operator in your query. 您不必在查询中使用$and运算符。 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 : 因此,您可以将此模式用于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 . 如果您仍然不确定为什么不使用$and运算符,请查看此答案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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