modelThreader.find({
$and: [
{"date_entered": { $lt: fromTime }},
{"cancelled": { $ne: true }},
{"hideFromUserIds.id": { $ne: current_user_id }},
{"banned": false},
{$and: [
{"user_id": { $ne: current_user_id }},
{"privacy": { $ne: 1 }}
]}
]
}).exec(function( err, docs ){
// handle response.
});
我在 mongo 中执行看似简单的查询时遇到了麻烦。
上面的查询我需要所有第一批都按照查询中的设置即:
{"date_entered": { $lt: fromTime }},
{"cancelled": { $ne: true }},
{"hideFromUserIds.id": { $ne: current_user_id }},
{"banned": false},
这工作正常,正如预期的那样。但是,由于文档架构已更改,我需要添加到此查询。
有一个新字段“隐私”,其中 int 1 是私有(private)的,只能返回给用户和所有人。正如你从我的查询中看到的,我想说的是
{$and: [
{"user_id": { $ne: current_user_id }},
{"privacy": { $ne: 1 }}
]}
即,如果current_user_id是请求查询的用户,则不应用任何隐私过滤器,否则,仅返回隐私不为1的文档。
问题在于它将 $ne:1 应用于所有用户,包括 current_user_id...
编辑 我能达到预期结果的唯一方法是做一个巨大的 $or 但这感觉效率低下:
其中 or 是其他 user_id 的数组
$or: [
{$and: [
//other people, respecting privacy
{$or: or},
{"date_entered": { $lt: fromTime }},
{"cancelled": { $ne: true }},
{"hideFromUserIds.id": { $ne: current_user_id }},
{"banned": false},
{"user_id": { $ne: current_user_id }},
{"privacy": { $ne: 1 }}
]},
{$and: [
//this user, not looking at privacy
{"date_entered": { $lt: fromTime }},
{"cancelled": { $ne: true }},
{"hideFromUserIds.id": { $ne: current_user_id }},
{"banned": false},
{"user_id": current_user_id }
]}
]})
最佳答案
您似乎在这里缺少明显的复合逻辑,其中只有“一小部分”相当于 $or
条件:
modelThreader.find({
"date_entered": { "$lt": fromTime },
"cancelled": { "$ne": true },
"banned": false,
"$or": [
{ "user_id": current_user_id },
{
"user_id": { "$ne": current_user_id },
"hideFromUserIds.id": { "$ne": current_user_id },
"privacy": { "$ne": 1 }
]
})
逻辑中的另一个“调整”是,“hideFromUserIds.id”
对于 current_user_id
与 “user_id”的匹配并不重要
因为已经是他们了。
ALL MongoDB 查询条件是“已经” 一个“AND”条件,除非另有明确说明。所以任何位于$or
“外部”的东西除了 $or
“内”应用的参数之外,还被视为“AND”表达式表达。
所以$or
里面唯一的东西是在逻辑分割中适用于“其他用户”的条件。否则,在所有情况下,其他所有内容都将作为“AND”应用。
最终你混淆了这些术语。因为当您的结果意味着您想要“其中任何一个条件以及除了其他结果”时,那么您实际上意味着 $or
关于javascript - $and with sub $and 在 mongo 和 mongoose 中没有产生预期结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36407262/