【问题标题】:How to check before updating an array element in MongoDB/NodeJS如何在更新 MongoDB/NodeJS 中的数组元素之前进行检查
【发布时间】:2015-08-16 15:10:31
【问题描述】:

在我的示例文档中,我有一个活动文档,其中包含文档的 _id 和一个 importData 数组。 importData 是一个包含唯一日期和源值的对象数组。

我的目标是使用唯一的日期/来源对更新对象。我想让新对象替换任何匹配的对象。在下面的示例中,Fred 最初可能捐赠了一台电视机,但我希望我的应用程序更新该对象以反映他捐赠了一台电视机和一台收音机。

// Events (sample document)
{
  "_id" : "Junky Joe's Jubilee",
  "importData" : [
    {
      "date": "2015-05-31",
      "source": "Fred",
      "items": [
        {item: "TV", value: 20.00},
        {item: "radio", value: 5.34}
      ]
    },
    {
      "date": "2015-05-31",
      "source": "Mary",
      "items": [
        {item: "Dresser", value: 225.00}
      ]
    }
  ]
}

我最初的想法是像下面的代码一样做一些事情,但我不仅要使用 Fred 的捐赠更新 importData,我还要吹走 importData 数组中的任何其他内容:

var collection = db.collection("events");
collection.update(
  {_id: "Junky Joe's Jubilee",
    importData: {
      date: "2015-05-31",
      source: 'Fred'
    },          
  },  // See if we can find a campaign object with this name
  {
    $set:
      {"importData": 
        {
          date: "2015-05-31",
          source: 'Fred',
          items: [
            {item: "TV", value: 20.00},
            {item: "radio", value: 5.34}
          ]
        }
      }
  },
  {upsert: true});  // Create a document if one does not exist for this campaign

当我尝试推送(而不是 $set)时,我收到了多个日期/来源组合条目(例如,Fred 似乎在“2015-05-31”上多次捐赠了两件物品)。

我将如何使用 MongoDB 原生驱动程序和 NodeJS 来做这件事?

【问题讨论】:

  • 你能把你的问题说清楚一点吗?

标签: arrays node.js mongodb


【解决方案1】:

试试这个

var collection = db.collection("events");
collection.update(
  {_id: "Junky Joe's Jubilee",
    importData: {
      date: "2015-05-31",
      source: 'Fred'
    },          
  },  // See if we can find a campaign object with this name
  {
    $set:
      {"importData.$": 
        {
          date: "2015-05-31",
          source: 'Fred',
          items: [
            {item: "TV", value: 20.00},
            {item: "radio", value: 5.34}
          ]
        }
      }
  },
  {upsert: true});  // Create a document if one does not exist for this campaign

根据Array update operators 下的文档,这应该只修改数组中与查询匹配的第一个元素。

【讨论】:

    猜你喜欢
    • 2017-01-05
    • 1970-01-01
    • 2022-06-11
    • 1970-01-01
    • 2013-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多