Node.js Mongoose$和过滤器不';t正确过滤
Mongoose中的Node.js Mongoose$和过滤器不';t正确过滤,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,Mongoose中的$和运算符在NodeJS中工作不正常。 假设我们有这个JSON MongoDB数据: { "_id" : ObjectId("60bb4cd74a802722d8b0de0f"), "username" : "System", "text" : "matan has joined!", "__v"
$和
运算符在NodeJS中工作不正常。
假设我们有这个JSON MongoDB数据:
{
"_id" : ObjectId("60bb4cd74a802722d8b0de0f"),
"username" : "System",
"text" : "matan has joined!",
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("60bb4cd74a802722d8b0de10"),
"username" : "System",
"text" : "Welcome!",
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("60bb4cdb4a802722d8b0de11"),
"username" : "matan",
"text" : "Hello World",
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("60bb4ce14a802722d8b0de12"),
"username" : "System",
"text" : "matan has left.",
"__v" : NumberInt(0)
}
我想过滤所有系统欢迎
消息将被删除的数据。例如,此输出将显示为:
{
"_id" : ObjectId("60bb4cd74a802722d8b0de0f"),
"username" : "System",
"text" : "matan has joined!",
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("60bb4cdb4a802722d8b0de11"),
"username" : "matan",
"text" : "Hello World",
"__v" : NumberInt(0)
}
{
"_id" : ObjectId("60bb4ce14a802722d8b0de12"),
"username" : "System",
"text" : "matan has left.",
"__v" : NumberInt(0)
}
但是,仅显示此输出:
{
_id: 60bb4cdb4a802722d8b0de11,
username: 'matan',
text: 'Hello World',
__v: 0
}
这是我的代码(NodeJS):
我错过什么重要的事了吗?谢谢您的帮助。请改用$or运算符
var msgs = Msg.find({
$or: [
{ username: {$ne: "System"} },
{ text: {$ne: "Welcome!"} }
]
}, (err, retn) => console.log(retn))
您可以使用聚合管道:
添加新字段$addFields
,如果满足两个要求(标志
等于用户名
,而系统
等于文本
),则该标志将为欢迎!
),否则为真
假
用于筛选新字段$match
等于false的所有文档标志
从最终结果中删除新字段$project
标志
以下是工作示例:带有
$ne
的$和
条件将匹配两个字段不应等于值
您可以尝试$或条件
var msgs = Msg.find({
$or: [
{ username: { $ne: "System" } },
{ text: { $ne: " Welcome!" } }
]
}, (err, retn) => console.log(retn))
我想过滤所有系统欢迎消息将被删除的数据=>为什么$ne
?使用$eq
。我需要除系统欢迎之外的所有数据。只需使用$or
而不是$和$or
就行了,因为其他人也可以发送欢迎代码>消息,或系统
可以发送不受欢迎的消息
@NenadMilosavljevic他只想排除系统的欢迎消息,$或不排除其他人的欢迎消息。再见,谢谢。成功了。
db.collection.aggregate([
{
"$addFields": {
"flag": {
"$cond": {
if: {
"$and": [
{
"$eq": [
"$username",
"System"
]
},
{
"$eq": [
"$text",
"Welcome!"
]
}
]
},
then: true,
else: false
}
}
}
},
{
"$match": {
"flag": false
}
},
{
"$project": {
"flag": 0
}
}
])
var msgs = Msg.find({
$or: [
{ username: { $ne: "System" } },
{ text: { $ne: " Welcome!" } }
]
}, (err, retn) => console.log(retn))