我有以下查询,它从文档中的两个数组(请求和关注者)中提取id:

   User.updateOne(
        { _id: otherUserId },
        { $pull: { requests: userId, followers: userId } }
    )

我想通过使用一个条件来修改这个查询,说明userId是否在requests数组中,然后从requests but don't update the followers array中拉取.如果id不在requests中,则从followers中拉出.目前,无论如何,这两个字段都会更新.有什么方法可以使用一个查询来实现这一点吗?

我try 了下面的代码,但它返回了CastError

 User.updateOne(
    { _id: otherUserId },
    { $pull: { requests: userId, followers: {$nin: [new mongoose.Types.ObjectId(userId), "$requests"]} }}
)

推荐答案

Aggregation Pipeline应该可以做到.

requests:

  • $filter -过滤requests数组以删除userId(如果存在).

followers:

  • $cond -判断userId不在requests数组中.
  • 如果为true,则从followers数组中删除userId.
  • 否则,保留followersarray.
User.updateOne(
{ _id: otherUserId },
[
  {
    $set: {
      requests: {
        $filter: {
          input: "$requests",
          cond: {
            $ne: [
              "$$this",
              userId
            ]
          }
        }
      },
      followers: {
        $cond: {
          if: {
            $not: {
              $in: [
                userId,
                "$requests"
              ]
            }
          },
          then: {
            $filter: {
              input: "$followers",
              cond: {
                $ne: [
                  "$$this",
                  userId
                ]
              }
            }
          },
          else: "$followers"
        }
      }
    }
  }
])

Demo @ Mongo Playground

Mongodb相关问答推荐

$mod只支持数字类型,不支持MongoDb中的array和int

MongoDB-如何过滤和获取数组字段中的最新数据

MongoDB查询优化

Mongodb Timeseries / Golang - ['timestamp' 必须存在并包含有效的 BSON UTC 日期时间值]

在 MongoDB 中加入多个集合

在MongoDb的数组中计算大于某个数字的数字

在 MongoDB 中,如何使用对当前值进行操作的函数来更新嵌套文档的值?

System.FormatException occurred in MongoDB.Bson.dll - XXX is not a valid 24 digit hex string

为什么 local.oplog.rs 上每隔几分钟的活动就会锁定 mongo 客户端

MongoDB 使用自定义表达式或函数进行排序

Mongo 重启错误 -- /var/run/mongodb/mongod.pid 存在

如何在 MongoDB 中进行内部连接?

升级mongodb

将 MongoDB 数据库复制到本地计算机

具有简单密码认证的 MongoDB 副本集

MongoDB count() 未定义

当前的 URL 字符串解析器已弃用

将 MongoCursor from ->find() 转换为数组

C# MongoDB 驱动程序 - 如何使用 UpdateDefinitionBuilder?

如何使用 MongoDB C# 驱动程序有条件地组合过滤器?