【问题标题】:How to update document if it exist and insert it if it doesn't exist in mongodb?如果存在,如何更新文档,如果在 mongodb 中不存在,如何将其插入?
【发布时间】:2021-12-20 01:06:33
【问题描述】:

这个问题与其他类似问题不同,因为 { upsert: true } 选项没有提供所需的输出。 我想更新/插入以下文档:

{
  _id: { 
    playerId: '1407081',
    tournamentId: '197831',
    matchId: '1602732' 
  },
  playerName: 'abcd',
  points: -5
}

执行下面给出的代码后,

await Points.findOneAndUpdate(
  {
    "_id": playerStatsObjForDB._id
  }, 
  {
    playerStatsObjForDB
  }, 
  {
    upsert: true
  }
);
//where playerStasObjForDB is same as object mentioned in top.

如果文档不存在,则插入以下文档:

{
  "_id": {
    "playerId":"1407081",
    "tournamentId":"197831",
    "matchId":"1602732"
  },
  "__v":0,
}

我正在使用猫鼬,但非常感谢任何帮助。

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

    MongoDB upsert 的工作方式如下:

        db.products.updateMany(
        { _id: 6 },
        { $set: {price: 999} },
        { upsert: true}
    )
    

    所以基本上第一个参数是查询本身,和你做的一样,但第二个应该是你想要修改的更新,你应该使用像 $set 这样的 MongoDB 操作符。 相反,您似乎将整个对象嵌入其中而没有修改。

    【讨论】:

    • 使用 $set 运算符解决了我的问题。
    猜你喜欢
    • 1970-01-01
    • 2014-02-16
    • 2019-01-16
    • 2011-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-03
    相关资源
    最近更新 更多