简体   繁体   English

如果文档存在,如何更新文档,如果它在 mongodb 中不存在,则如何插入?

[英]How to update document if it exist and insert it if it doesn't exist in mongodb?

This question is different from other similar questions because { upsert: true } option doesn't give desired output.这个问题与其他类似问题不同,因为 { upsert: true } 选项没有给出所需的输出。 I want to update/insert the given below document:我想更新/插入以下给定的文档:

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

After executing the given below code,执行下面给出的代码后,

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

if the document doesn't exist, it inserts the following document:如果文档不存在,则插入以下文档:

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

I am using mongoose, but any help is greatly appreciated.我正在使用猫鼬,但非常感谢任何帮助。

Well MongoDB upsert works in the following way:那么 MongoDB upsert 的工作方式如下:

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

So basically the first parameter is the query itself the same way you did, but the second one should be the updates you want to modify and you should use MongoDB operators like $set.所以基本上第一个参数是查询本身,就像你所做的一样,但第二个参数应该是你想要修改的更新,你应该使用像 $set 这样的 MongoDB 操作符。 Instead, it seems that you embedded the entire object inside it without modifications.相反,您似乎没有修改就将整个对象嵌入其中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM