mongoose查询regex以忽略中间字符



我正在使用mongodb,我的数据存储为day:"3/6/2020">我想查询与day:"3/2020"配的字符串,不带中间值或省略day:"3/6/2002"

`myModel.find({"day": {$regex: "3/2020",  $options:" what option to pass here to ignore the `
` middle value"}});`
or any better way
`model.find({"name": {$regex: search, $options:" regex options"}}, (err, users)=> {`
`  res.status(200).send({users});`

"2020年3月">32020匹配任何记录,就像此"2020年6月3日"与

我想您可以使用聚合框架将字符串日期转换为正确的日期,获取月份和年份并与之匹配。像这样的

model.aggregate([{
"$addFields": {
"convertedDate": {
"$toDate": "$myDate" // mydate is your field name which has string
}
}
}, {
"$addFields": {
"month": {
"$month": "$convertedDate"
},
"year": {
"$year": "$convertedDate"
}
}
}, {
"$match": {
"month": 3, // this is your search criteria
"year": 2020 // // this is your search criteria
}
}, {
"$project": {
"month": 0, // Do not take temp added fields month and year 
"year": 0 // Do not take temp added fields month and year 
}
}])

这看起来可能是一个大查询,但我想这比使用regex进行字符串合并要好得多。如果您的字段以日期格式保存,您还可以删除执行$toDate的第一阶段。希望这能帮助

这可能会对您有所帮助。我们匹配3,而不是一个一两个字符宽的数字,然后在2020年底。

3/d{1,2}/2020

https://regex101.com/r/jn4zwa/1

Solved. i solved it  splitting my date as in my schema
```
qDay :{
type:Number, default: new Date().getDate(Date.now)
},
qMonth :{
type:Number, default: new Date().getMonth(Date.now) + 1
},
qYear :{
type:Number, default: new Date().getFullYear(Date.now)
}```
my query

```const getByDay = async (req, res)=> {
console.log(req.body);
merchantModel.find({$and:[{qMonth : req.body.month}
,{qYear: req.body.year},{qDay:req.body.day}]}).then((record)=> {
if(record.length == 0){
res.status(404).send({msg:'no record!'});
}else{
co`enter code here`nsole.log(record);
res.status(200).send({record:record});
}
});
}```

最新更新