gpt4 book ai didi

node.js - MongoDB:查找除日期范围条件匹配的文档之外的所有文档

转载 作者:IT老高 更新时间:2023-10-28 13:23:11 27 4
gpt4 key购买 nike

要求:我想要收集所有在过去 5 小时内没有执行“查看”事件的客户

数据:

{
name: "Sheldon",
events: [
{
event: "View",
timestamp: "timestamp equivalent to 10 hours ago"
},
{
event: "Some other event",
timestamp: "timestamp equivalent to 8 hours ago"
},
{
event: "View",
timestamp: "timestamp equivalent to 2 hours ago"
}
]
},
{
name: "Leonard",
events: [
{
event: "View",
timestamp: "timestamp equivalent to 10 hours ago"
}
]
},
{
name: "Howard",
events: [
{
event: "View",
timestamp: "timestamp equivalent to 2 hours ago"
}
]
},
{
name: "Raj",
events: [
{
event: "Some other event",
timestamp: "timestamp equivalent to 6 hours ago"
}
]
}

我尝试了以下方法,但它总是返回 "Sheldon"(可能是因为其他事件最终满足条件?)。

q.where({ 
$and: [
{
'events': {
$not: {
$elemMatch: {
event: "View",
timestamp: {
$gte: "timestamp equivalent to 5 hours ago"
}
}
}
}
}
]
});

我该怎么做才能只返回 "Leonard""Raj" 的文档?

最佳答案

获取过去 5 小时内未访问过的用户。你可以试试

db.collectionName.find({
events: {
$not: {
$elemMatch: {
event: "View",
timestamp: {
$gt: ISODate("2017-03-29T05:12:37.420Z") // equivalent to 5 hours ago
}
}
}
}
}, {name: 1})

此查询 returned 仅记录您给定示例的 LeonardRaj

注意: 喜欢您的查询,但我使用 find 而不是 where,无需使用 $and并使用 $gt 而不是 $gte

已针对文档进行测试。

{
"_id" : ObjectId("58db886e4b9e731aaefa9820"),
"name" : "Sheldon",
"events" : [
{
"event" : "View",
"timestamp" : ISODate("2017-03-29T00:09:18.723Z")
},
{
"event" : "Some other event",
"timestamp" : ISODate("2017-03-29T02:10:04.492Z")
},
{
"event" : "View",
"timestamp" : ISODate("2017-03-29T08:11:02.196Z")
}
]
}
{
"_id" : ObjectId("58db886e4b9e731aaefa9821"),
"name" : "Leonard",
"events" : [
{
"event" : "View",
"timestamp" : ISODate("2017-03-29T00:11:23.084Z")
}
]
}
{
"_id" : ObjectId("58db886e4b9e731aaefa9822"),
"name" : "Howard",
"events" : [
{
"event" : "View",
"timestamp" : ISODate("2017-03-29T08:11:02.196Z")
}
]
}
{
"_id" : ObjectId("58db886e4b9e731aaefa9823"),
"name" : "Raj",
"events" : [
{
"event" : "Some other event",
"timestamp" : ISODate("2017-03-29T04:10:42.972Z")
}
]
}

应用我的查询结果后:

{
"_id" : ObjectId("58db886e4b9e731aaefa9821"),
"name" : "Leonard"
},
{
"_id" : ObjectId("58db886e4b9e731aaefa9823"),
"name" : "Raj"
}

关于node.js - MongoDB:查找除日期范围条件匹配的文档之外的所有文档,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43089013/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com