【发布时间】:2022-02-01 11:30:19
【问题描述】:
我需要搜索一个大型 mongo 集合并找到所有在 createdAt 后至少 7 天更新的文档。
我的数据基本上是这样的:
"createdAt" : ISODate("2021-04-03T10:17:21.256Z"),
"updatedAt" : ISODate("2021-04-03T10:17:21.256Z")
我将不胜感激。
【问题讨论】:
我需要搜索一个大型 mongo 集合并找到所有在 createdAt 后至少 7 天更新的文档。
我的数据基本上是这样的:
"createdAt" : ISODate("2021-04-03T10:17:21.256Z"),
"updatedAt" : ISODate("2021-04-03T10:17:21.256Z")
我将不胜感激。
【问题讨论】:
在匹配中使用$expr。 $dateAdd 仅在 mongodb 5.0 中可用。
db.collection.aggregate([
{
"$match": {
$expr: {
$gt: [
"$updatedAt",
{
$dateAdd: {
startDate: "$createdAt",
unit: "day",
amount: 7
}
}
]
}
}
}
])
604800000 = 7 * 24 * 60 * 60 * 1000
db.collection.aggregate([
{
"$match": {
$expr: {
$gt: [
"$updatedAt",
{
$add: [
"$createdAt",
604800000
]
}
]
}
}
}
])
使用$where
db.collection.find({
"$where": "this.updatedAt > new Date(this.createdAt.getTime() + 604800000)"
})
【讨论】:
$add更新我的答案
$expr 和 $gt 和 $add 在 mongodb 3.6 中可用
$where更新我的答案