如何在MongoDB中按指定年月检索目标文档?
MongoDB查询:同时匹配指定年份和月份的文档
需求说明
需要从expenses集合中检索满足以下条件的文档:
- 包含指定的用户名(
users.username匹配目标值) date字段属于指定的年份和月份(例如2020年9月,应返回前两个文档)
集合示例数据
[ { _id: ObjectId("65708c6237b62067296a398f"), date: ISODate("2020-09-15T04:07:05.000Z"), description: 'playstation', category: 'miscellaneous', cost: 499, users: [ { username: 'Giacomo', amount: 499 } ] }, { _id: ObjectId("6570950cecb7eb1b4b868409"), date: ISODate("2020-09-15T04:07:05.000Z"), description: 'tennis court', category: 'sport', cost: 100, users: [ { username: 'prova', amount: 50 }, { username: 'Giacomo', amount: 50 } ] }, { _id: ObjectId("6570953aecb7eb1b4b86840a"), date: ISODate("2023-02-09T03:12:15.012Z"), description: 'netflix subscription', category: 'entertainment', cost: 100, users: [ { username: 'prova', amount: 10 } ] } ]
当前已实现的查询(仅匹配年份)
db .collection("expenses") .find({ "users.username": "desired_username", $expr: { $eq: [{ $year: "$date" }, 2020] }, })
解决方案
方法1:使用$expr结合$and同时匹配年份和月份
在$expr中通过$and操作符组合年份和月份的判断条件:
db.collection("expenses").find({ "users.username": "desired_username", $expr: { $and: [ { $eq: [{ $year: "$date" }, 2020] }, { $eq: [{ $month: "$date" }, 9] } ] } })
该查询会同时校验date字段的年份为2020、月份为9,并且保留用户名匹配条件。
方法2:使用日期范围查询(推荐,性能更优)
直接通过date字段的范围进行匹配,这种方式可以利用date字段上的索引,查询效率更高。以2020年9月为例,范围是2020年9月1日0点到2020年10月1日0点(左闭右开):
db.collection("expenses").find({ "users.username": "desired_username", date: { $gte: ISODate("2020-09-01T00:00:00.000Z"), $lt: ISODate("2020-10-01T00:00:00.000Z") } })
内容的提问来源于stack exchange,提问作者Eminent Emperor Penguin
相关产品推荐
相关产品推荐

