MongoDB:当 arrayFilters 找不到匹配项时进行更新 [英] MongoDB: upsert when arrayFilters can't find a match

查看:64
本文介绍了MongoDB:当 arrayFilters 找不到匹配项时进行更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的集合:

读者

[{
    "id": 123,
    "name": "John Doe",
    "books": [
      {
        "type": "comic",
        "names": [
          "batman",
          "tintin"
        ]
      },
      {
        "type": "drama",
        "names": [
          "hamlet",
          "otelo"
        ]
      }
    ]
 },
 {...}]

然后我想更新我的集合,添加数组 names 匹配 type.

Then I want to update my collection adding in array names matching by type.

type 存在时完美运行,在这个例子中 romeo and juliet 被正确推送:

When type exists works perfectly, in this example romeo and juliet is pushed correctly:

db.collection('readers').updateOne(
    { id: 123 },           
    {
      $push: {
        'books.$[element].names': 'romeo and juliet'
      }
    },
    {
      upsert: true,
      arrayFilters: [{ 'element.type': 'drama' }] // type exists
    }
  );

问题来了type不匹配时:

The problem come when type is not matched:

db.collection('readers').updateOne(
    { id: 123 },           
    {
      $push: {
        'books.$[element].names': 'hobbit'
      }
    },
    {
      upsert: true,
      arrayFilters: [{ 'element.type': 'fantasy' }] // new type
    }
  );

我期待这个结果,但没有添加任何内容:

I expect this result but nothing is added:

{
   "id": 123,
   "name": "John Doe",
   "books": [
    {
      "type": "comic",
      "names": [
        "batman",
        "tintin"
      ]
    },
    {
      "type": "drama",
      "names": [
         "hamlet",
         "otelo"
      ]
    },
    {
      "type": "fantasy",
      "names": [
         "hobbit"             
      ]
    }
  ]
}

我做错了什么?

推荐答案

您希望 upsert 创建丢失的书,但它不是如何工作的.

You expect upsert to create the missing book but it's not how it works.

Upsert:如果设置为true,当没有文档时创建一个新文档匹配查询条件.默认值为 false,不会找不到匹配项时插入新文档.

Upsert: If set to true, creates a new document when no document matches the query criteria. The default value is false, which does not insert a new document when no match is found.

我认为您已经创建了 2 个查询,一个用于检查这本书是否存在,另一个用于更新/创建它(推送或您创建这本书)

I think you have create 2 queries, one to check if the book exists and another one to update/create it (either push or you create the book)

这篇关于MongoDB:当 arrayFilters 找不到匹配项时进行更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆