Node.js Mongoose$和过滤器不';t正确过滤

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"

Mongoose中的
$和
运算符在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))