【问题标题】:MongoDB/Mongoose querying documents between certain dates?MongoDB/Mongoose 在特定日期之间查询文档?
【发布时间】:2018-08-09 09:12:39
【问题描述】:

我希望它在特定日期之间获取文档,我知道我需要使用 $and 运算符,但现在我正在使用 Querymen,MongoDB 的中间件,我阅读了文档,但我找不到任何相关内容。

我正在做的是这样的:

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

所以我的问题是如何使用 $and 运算符

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

    您不必在查询中使用$and 运算符。而不是这个:

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

    你可以这样做:

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

    因此,您可以将此架构用于 querymen

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

    完整示例可能如下所示:

    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'));
    

    如果您仍然怀疑为什么不使用$and 运算符,请查看this answer

    【讨论】:

    • 谢谢,我以不同的方式解决了它,但它很混乱,你的解决方案更加优雅,而且我不知道没有必要使用 $and 运算符
    猜你喜欢
    • 2012-08-11
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-27
    • 2020-08-02
    相关资源
    最近更新 更多