我有类似这样的数据
{
"_id": ObjectId("52ed12c144aecc4bf004d0b6"),
"active": true,
"name": "woslo",
"specialDays": [
{
"_id": ObjectId("5f0576196198a715b0a72c14")
"status": true
"date": 2020-07-08T04:00:00.000+00:00
},
{
"_id": ObjectId("5f05a3726198a715b0a72c94")
"status": false
"date": 2020-07-09T04:00:00.000+00:00
}
]
}
我想使用此查询来获取记录
db.serviceProviders.aggregate([ { $match: { specialDays: { $elemMatch: { $or: [ { $and: [ { date: model.date // 2020-07-09T06:00:00.000Z }, { status: true } ] }, { date: { $ne: model.date //2020-07-09T06:00:00.000Z } } ] } } } } ]);
场景为:如果date在specialDays数组中存在,并且状态应为true,或者date不应在specialDays对象的数组中,则获取此记录。 但是,每次获取甚至高于状态的同一记录时,其结果都是false或数组中存在日期。 您能帮我解决这个问题吗,我使用 ISODate('2020-07-08')在Mongo罗盘汇总中尝试了很多查询,但仍然无法正常工作。 谢谢 编码愉快。
答案 0 :(得分:2)
问题与您的$ne
条件有关。如果状态为false,则您的$ne
条件为true。由于它是逻辑OR,因此您将获得输出。
this怎么样?
db.collection.aggregate([
{
$match: {
specialDays: {
$elemMatch: {
$or: [
{
$and: [
{
date: new Date("2020-07-09T04:00:00.000+00:00")
},
{
status: true
}
]
},
{
date: {//Changes here
$gte: new Date("2020-07-09T06:00:00.000+00:00"),
$lte: new Date("2020-07-09T23:59:59.000+00:00")
}
}
]
}
}
}
}
])
OR
您的$ne
条件的另一个原因是正确的,因为它满足了specialDays
数组中的第一个数组元素
db.collection.aggregate([
{
$match: {
specialDays: {
$elemMatch: {
$or: [
{
$and: [
{
date: new Date("2020-07-09T04:00:00.000+00:00")
},
{
status: true
}
]
},
{
$and: [
{
date: {
$ne: new Date("2020-07-09T04:00:00.000+00:00")
}
},
{
status: false
}
]
}
]
}
}
}
}
])