能否请您告诉我如何在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"
}
})
答案 0 :(得分:1)
我建议(如注释中所述)在文档中将日期存储为date object
,以有效地使用日期操作并避免转换。
要解决这种情况,您可以将aggregation
与$match
,$addFields
,$toDate
和ISODate
一起使用。
db.collection.aggregate([
{
$addFields: {
formattedDate: {
$toDate: "$Att Date"
}
}
},
{
$match: {
formattedDate: {
$gte: ISODate("2019-01-01"),
$lte: ISODate("2019-01-31")
}
}
}
]);
注意:在mongo游乐场link上进行了更新。
$addFields
将Att Date
转换为ISODate
并将其传递到下一个阶段。$match
接受本质上为formattedDate
的{{1}}并与传递的日期字符串进行比较(使用Att Date
转换)。ISODate
删除该formattedDate
。答案 1 :(得分:0)
使用汇总管道,我们可以获得预期的结果
Att Date
)转换为Date对象。
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") ] } ] }
}
}
]
)