Luc*_*fim 8 mongodb mongodb-php mongodb-query
如何查询mongodb中的特定月份,而不是日期范围,我需要月份来制作当月的客户生日列表.
在SQL中将是这样的:
SELECT * FROM customer WHERE MONTH(bday)='09'
Run Code Online (Sandbox Code Playgroud)
现在我需要在mongodb中翻译它.注意:我的日期已经保存在MongoDate类型中,我用这种思维方式以前很容易上班,但现在我找不到如何做这个简单的事情.
chr*_*dam 15
使用MongoDB 3.6及更高版本,您可以$expr在find()查询中使用运算符.这允许您构建查询表达式,以比较$match阶段中同一文档的字段.
db.customer.find({ "$expr": { "$eq": [{ "$month": "$bday" }, 9] } })
Run Code Online (Sandbox Code Playgroud)
对于其他MongoDB版本,请考虑运行使用$redact运算符的聚合管道,因为它允许您与单个管道合并,$project用于创建表示日期字段月份的字段以及$match过滤与给定条件匹配的文档的功能这个月是九月.
在上文中,$redact使用$condtenary运算符作为提供条件表达式的手段,该条件表达式将创建执行编校的系统变量.逻辑表达式$cond将检查具有给定值的日期运算符字段是否相等,如果匹配则将$redact使用$$KEEP系统变量返回文档,否则使用丢弃$$PRUNE.
运行以下管道应该可以获得所需的结果:
db.customer.aggregate([
{ "$match": { "bday": { "$exists": true } } },
{
"$redact": {
"$cond": [
{ "$eq": [{ "$month": "$bday" }, 9] },
"$$KEEP",
"$$PRUNE"
]
}
}
])
Run Code Online (Sandbox Code Playgroud)
这类似于$project+ $match组合,但您需要选择进入管道的所有其他字段:
db.customer.aggregate([
{ "$match": { "bday": { "$exists": true } } },
{
"$project": {
"month": { "$month": "$bday" },
"bday": 1,
"field1": 1,
"field2": 1,
.....
}
},
{ "$match": { "month": 9 } }
])
Run Code Online (Sandbox Code Playgroud)
使用另一种方法,尽管查询速度慢,使用find()方法$where:
db.customer.find({ "$where": "this.bday.getMonth() === 8" })
Run Code Online (Sandbox Code Playgroud)
你可以做,使用aggregate与$month投影算:
db.customer.aggregate([
{$project: {name: 1, month: {$month: '$bday'}}},
{$match: {month: 9}}
]);
Run Code Online (Sandbox Code Playgroud)
小智 7
是的,您可以在这样的日期内获取此结果,
db.collection.find({
$expr: {
$and: [
{
"$eq": [
{
"$month": "$date"
},
3
]
},
{
"$eq": [
{
"$year": "$date"
},
2020
]
}
]
}
})
Run Code Online (Sandbox Code Playgroud)
首先,您需要检查数据类型是否在 ISODate 中。如果不是,您可以更改数据类型,如下例所示。
db.collectionName.find().forEach(function(each_object_from_collection){each_object_from_collection.your_date_field=new ISODate(each_object_from_collection.your_date_field);db.collectionName.save(each_object_from_collection);})
Run Code Online (Sandbox Code Playgroud)
现在你可以通过两种方式找到它
db.collectionName.find({ $expr: {
$eq: [{ $year: "$your_date_field" }, 2017]
}});
Run Code Online (Sandbox Code Playgroud)
或者通过聚合
db.collectionName.aggregate([{$project: {field1_you_need_in_result: 1,field12_you_need_in_result: 1,your_year_variable: {$year: '$your_date_field'}, your_month_variable: {$month: '$your_date_field'}}},{$match: {your_year_variable:2017, your_month_variable: 3}}]);
Run Code Online (Sandbox Code Playgroud)