过滤日期在Mongoldb中不起作用

时间:2019-09-20 07:25:05

标签: node.js mongodb mongoose

能否请您告诉我如何在MongoDB中按日期参数过滤数据? 我喜欢这样 https://mongoplayground.net/p/72LzlP1Sr5W

import initApollo from './initApollo'

function parseCookies (req, options = {}) {
  return cookie.parse(req ? req.headers.cookie || '' : document.cookie, options)
}

export default App => {
  return class WithData extends React.Component {
    // It is needed for better devtools experience. Check how react devtools shows it: "MyApp WithData"
    static displayName = `WithData(${App.displayName})`

    // Since apolloState is required but it is missed before this method returns the new props,
    // so it is needed to provide defaults
    static defaultProps = {
      apolloState: {}
    }

    static propTypes = {
      apolloState: PropTypes.object.isRequired
    }

    static async getInitialProps (ctx) {
      const { AppTree, ctx: { req, res }} = ctx
      const apollo = initApollo(
        {},
        {
          getToken: () => parseCookies(req).token
        }
      )

      ctx.ctx.apolloClient = apollo

      let appProps = {}
      if (App.getInitialProps) {
        appProps = await App.getInitialProps(ctx)
      }

      if (res && res.finished) {
        // When redirecting, the response is finished.
        // No point in continuing to render
        return {}
      }

      if (typeof window === 'undefined') {
        // Run all graphql queries in the component tree
        // and extract the resulting data
        try {
          // Run all GraphQL queries
          await getDataFromTree(<AppTree {...appProps} apolloClient={apollo} />)
        } catch (error) {
          // Prevent Apollo Client GraphQL errors from crashing SSR.
          // Handle them in components via the data.error prop:
          // https://www.apollographql.com/docs/react/api/react-apollo.html#graphql-query-data-error
          console.error('Error while running `getDataFromTree`', error)
        }

        // getDataFromTree does not call componentWillUnmount
        // head side effect therefore need to be cleared manually
        Head.rewind()
      }

      // Extract query data from the Apollo's store
      const apolloState = apollo.cache.extract()

      return {
        ...appProps,
        apolloState
      }
    }

    constructor (props) {
      super(props)
      // `getDataFromTree` renders the component first, the client is passed off as a property.
      // After that rendering is done using Next's normal rendering pipeline
      // @ts-ignore
      this.apolloClient = initApollo(props.apolloState, {
        getToken: () => {
          // @ts-ignore
          return parseCookies().token
        }
      })
    }

    render () {
      // @ts-ignore
      return <App apolloClient={this.apolloClient} {...this.props} />
    }
  }
}

当前没有显示该查询的文档

期望

db.collection.find({
  "Att Date": {
    $gte: "2019-01-01",
    $lte: "2019-01-31"
  }
})

2 个答案:

答案 0 :(得分:1)

我建议(如注释中所述)在文档中将日期存储为date object,以有效地使用日期操作并避免转换。

要解决这种情况,您可以将aggregation$match$addFields$toDateISODate一起使用。

db.collection.aggregate([
  {
    $addFields: {
      formattedDate: {
        $toDate: "$Att Date"
      }
    }
  },
  {
    $match: {
      formattedDate: {
        $gte: ISODate("2019-01-01"),
        $lte: ISODate("2019-01-31")
      }
    }
  }
]);

注意:在mongo游乐场link上进行了更新。

  1. $addFieldsAtt Date转换为ISODate并将其传递到下一个阶段。
  2. $match接受本质上为formattedDate的{​​{1}}并与传递的日期字符串进行比较(使用Att Date转换)。
  3. 如果需要,您可以在下一阶段的投影中使用ISODate删除该formattedDate

答案 1 :(得分:0)

使用汇总管道,我们可以获得预期的结果

  1. 使用$project将所有必需的属性投影到下一阶段 在此第一个投影中-使用$dateFromString
  2. 将字符串日期(Att Date)转换为Date对象。
  3. 再次使用$project并在属性(Att Date上应用条件$ gte和$ lte以获得所需的结果

查询以获取结果

db.collection.aggregate([
  {
    $project: {
      _id: 1,
      "Emp No": 1,
      "Emp Name": 1,
      "Card No": 1,
      "Department": 1,
      "In Time": 1,
      "Out Time": 1,
      "Status": 1,
      "Late By ": 1,
      "Early By ": 1,
      "Total Hour": 1,
      "OT Hour": 1,
      "Location": 1,
      "id": 1,
      "Att Date": {
        $dateFromString: {
          dateString: '$Att Date'
        }
      }
    }
  }, 
 {
    $project: {
      _id: 1,
      "Emp No": 1,
      "Emp Name": 1,
      "Card No": 1,
      "Department": 1,
      "In Time": 1,
      "Out Time": 1,
      "Status": 1,
      "Late By ": 1,
      "Early By ": 1,
      "Total Hour": 1,
      "OT Hour": 1,
      "Location": 1,
      "id": 1,
      "Att Date": { "$and": [ {$gte: [ "$Att Date", new Date("2019-01-01") ]}, {$lte: 
     [ "$Att Date", new Date("2019-01-31") ] } ] }
    }
 }
]
)