我正在尝试对 mongoDB 进行简单或查询,但确实收到错误 MongoError:未知运算符:$ 或
有人可以解释我做错了什么吗?
const query = {
title: { $exists: true },
category: { $exists: true, $ne: [] }
}
// ...do some stuff
// now need to change category query...
query.category = {
$or: [
{ $exists: false },
{ $eq: [] }
]
}
// should return documents with missing category field or empty array value
Content.find(query)
最佳答案
简短的回答是 $or
语句不适用于单个字段,而是必须为每个项目指定字段:
$or: [
{category: {$exists: false}},
{category: {$eq: []}}
]
解释根据 the manual ,
$or
语法如下:{ $or: [ { <expression1> }, { <expression2> }, ... , { <expressionN> } ] }
请注意,与许多运算符不同,它不包含字段名称。例如,对比
$exists
,其中确实包括字段名称:{ field: { $exists: <boolean> } }
换句话说,而不是:
{
title: { $exists: true },
category: {
$or: [
{$exists: false},
{$eq: []}
]
}
}
你需要:{
title: { $exists: true },
$or: [
{category: {$exists: false}},
{category: {$eq: []}}
]
}
问题的例子将所有这些与您的确切示例放在一起,您最终会得到:
const query = {
title: { $exists: true },
category: { $exists: true, $ne: [] }
}
// ...do some stuff
// now need to change category query...
delete query.category
query.$or = [
{category: {$exists: false}},
{category: {$eq: []}}
]
// should return documents with missing category field or empty array value
Content.find(query)
关于javascript - MongoDB:未知运算符:$ 或,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48530123/