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

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

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

问题

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

  1. {
  2. "_id": {
  3. "$oid": "63ef95daf324e5a26354eb61"
  4. },
  5. "idCarga": "6182944",
  6. "12121212121212": {
  7. "info1": "hello",
  8. "info2": "goodbye"
  9. },
  10. "13131313131313": {
  11. "info1": "hello",
  12. "info2": "goodbye"
  13. }
  14. }

我的目标是:

  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:

  1. {
  2. "_id": {
  3. "$oid": "63ef95daf324e5a26354eb61"
  4. },
  5. "idCarga": "6182944",
  6. "12121212121212": {
  7. "info1": "hello",
  8. "info2": "goodbye"
  9. },
  10. "13131313131313": {
  11. "info1": "hello",
  12. "info2": "goodbye"
  13. }
  14. }

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

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

  1. db.collection.update({
  2. <您的条件>
  3. },[
  4. {
  5. $set: {
  6. "<您的ID>": {
  7. "$ifNull": [
  8. "$<您的ID>",
  9. {
  10. <您的新子文档>
  11. }
  12. ]
  13. }
  14. }
  15. }
  16. ])

Mongo Playground 用于新ID情况

Mongo Playground 用于现有ID情况

英文:

Simply do a $set with $ifNull

  1. db.collection.update({
  2. &lt;your criteria&gt;
  3. },[
  4. {
  5. $set: {
  6. &quot;&lt;your id&gt;&quot;: {
  7. &quot;$ifNull&quot;: [
  8. &quot;$&lt;your id&gt;&quot;,
  9. {
  10. &lt;your new sub doc&gt;
  11. }
  12. ]
  13. }
  14. }
  15. }
  16. ])

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:

确定