在MongoDB中只有在字段不存在时才插入字段的任何方法?

huangapple go评论109阅读模式
英文:

Any way to insert fields only if they don't already exist in MongoDB?

问题

我尝试了一些我找到的解决方案,但我不明白这应该如何工作(我是Mongo的新手)。我有一个看起来像这样的文档:

{
  "_id": {
    "$oid": "63ef95daf324e5a26354eb61"
  },
  "idCarga": "6182944",
  "12121212121212": {
    "info1": "hello",
    "info2": "goodbye"
  },
  "13131313131313": {
    "info1": "hello",
    "info2": "goodbye"
  }
}

我的目标是:

  1. 如果我尝试使用新的产品ID字段(如15151515151515)更新文档,它将作为新字段插入。
  2. 如果我尝试使用已经存在的产品ID(如13131313131313)更新文档,什么都不会发生(不会插入或更新任何内容)。

我使用$exists运算符与upsert选项得到了一些结果。但我必须插入如此多的产品ID,这似乎是一个不可行的选项。是否有办法只使用一个文档来实现这一目标?还是我必须将其拆分为两个集合?先感谢您。

英文:

I've tried some solutions i've found but im not getting how this is supposed to work (im new to mongo). i have a document that looks like this:

{
  "_id": {
    "$oid": "63ef95daf324e5a26354eb61"
  },
  "idCarga": "6182944",
  "12121212121212": {
    "info1": "hello",
    "info2": "goodbye"
  },
  "13131313131313": {
    "info1": "hello",
    "info2": "goodbye"
  }
}

My goal is to:

  1. If i try to update the document with a new product ID field (like 15151515151515), it gets inserted as a new field.
  2. If i try to update the document with an already existing prod ID (like 13131313131313), nothing happens (dont insert or update anything).

I got some results with the $exists operator paired with upsert option. But i have to insert so many product IDs it seems like an unviable option. Is there any way to do this with only one document per "idCarga"? Or do i have to separate this into 2 collections? Thanks in advance.

答案1

得分: 0

以下是代码部分的中文翻译:

db.collection.update({
  <您的条件>
},[
  {
    $set: {
      "<您的ID>": {
        "$ifNull": [
          "$<您的ID>",
          {
            <您的新子文档>
          }
        ]
      }
    }
  }
])

Mongo Playground 用于新ID情况

Mongo Playground 用于现有ID情况

英文:

Simply do a $set with $ifNull

db.collection.update({
  &lt;your criteria&gt;
},[
  {
    $set: {
      &quot;&lt;your id&gt;&quot;: {
        &quot;$ifNull&quot;: [
          &quot;$&lt;your id&gt;&quot;,
          {
            &lt;your new sub doc&gt;
          }
        ]
      }
    }
  }
])

Mongo Playground for new id case

Mongo Playground for existing id case

huangapple
  • 本文由 发表于 2023年2月17日 23:42:57
  • 转载请务必保留本文链接:https://go.coder-hub.com/75486400.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定