如果不存在mongodb,则设置文档字段

qcuzuvrc  于 2022-11-03  发布在  Go
关注(0)|答案(1)|浏览(157)

我有一个mongodb文档,我想设置一个字段,如果不存在,否则,如果字段存在,我想保持它,因为它是,我不知道是什么错误与我的代码:

await UserAnalytics.findOneAndUpdate(
      { user },
      {
        $inc: {
          nbPosts: 1,
        },
      },
      {
        $cond: [
          { bestPost: { $exists: false } },
          { $set: { bestPost: newPost._id } },
          { $set: { bestPost: "$bestPost" } },
        ],
      }
    );

有什么需要帮忙的吗?

zxlwwiss

zxlwwiss1#

为了在更新查询中使用Aggregation框架,您需要用[] Package 第二个输入:

db.collection.update({
  user: 1
},
[
  {
    "$set": {
      "nbPosts": {
        "$sum": [
          "$nbPosts",
          1
        ]
      },
      "bestPost": {
        "$cond": {
          "if": {
            "$eq": [
              "$bestPost",
              undefined
            ]
          },
          "then": "new_id",
          "else": "$bestPost"
        }
      }
    }
  }
])

Working example

相关问题