javascript - 如何有条件地从 MongoDB 中的对象数组中删除一个字段?

标签 javascript node.js mongodb mongoose

我有一个包含以下文档的 Listing 集合:

{
  owner: ObjectId('12345678'),
  bids: [
    {
      amount: 36,
      date: 2021-06-23T21:00:00.000+00:00,
      placedBy: ObjectId('1111111')
    },
    {
      amount: 16,
      date: 2021-06-23T21:00:00.000+00:00,
      placedBy: ObjectId('22223332')
    }
  ]
}
我需要查询 bids 数组,但只有在满足 条件时才删除字段 placedBy(对于数组中的所有元素)
这是我到目前为止:
async getBids(listingId: string, user: UserDocument) {
        return this.listingModel.aggregate([
            { $match: { _id: Types.ObjectId(listingId) } },
            {
                $project: {
                    'bids.date': 1,
                    'bids.amount': 1,
                    'bids.placedBy': {
                        $cond: {
                            if: {
                                '$eq': ['$owner', Types.ObjectId(user.id)]
                            },
                            then: '$bids.placedBy',
                            else: '$$REMOVE'
                        }
                    }
                }
            }
        ])
    }
这适用于条件为 false ( bids.placedBy 已删除)的情况,但是当条件满足时,我得到了这个( bids.placedBy 变成了所有 placedBy 的数组):
bids: [
    {
      amount: 36,
      date: 2021-06-23T21:00:00.000+00:00,
      placedBy: [
        ObjectId('1111111'),
        ObjectId('22223332')
      ]
    },
    {
      amount: 16,
      date: 2021-06-23T21:00:00.000+00:00,
      placedBy: [
        ObjectId('1111111'),
        ObjectId('22223332')
      ]
    }
  ]
我怎样才能解决这个问题?

最佳答案

您可以使用 $map遍历数组并设置条件

db.collection.aggregate([
  {
    $project: {
      "bids": {
        "$map": {
          "input": "$bids",
          "in": {
            amount: "$$this.amount",
            date: "$$this.date",
            placedBy: {
              $cond: [ { "$eq": [ "$owner", 1 ] }, "$$this.placedBy", "$$REMOVE" ]
            }
          }
        }
      }
    }
  }
])
工作Mongo playground

关于javascript - 如何有条件地从 MongoDB 中的对象数组中删除一个字段?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68053321/

相关文章:

json - mongoexport JSON 断言 : 10340 Failure parsing JSON string

javascript - 显示 <li> 中 2 个数组的元素

javascript - 将 e.location 字符串拆分为变量

javascript - 如何在自身内部渲染 React 组件

node.js - webpack-dev-middleware 与 create-react-app

javascript - promise 中的 promise

mongodb - 如何在MongoDB Atlas中获取 'full database name'?

javascript - 将 .slideUp() 和 .slideDown() 添加到搜索结果?

node.js - ts-node:意外 token ':'

node.js - 如何通过 Express 中的中间件链识别请求(通过 ID)。