如何在更新MongoDB / NodeJS中的数组元素之前进行检查

时间:2015-06-02 17:22:45

标签: arrays node.js mongodb

在我的示例文档中,我有一个包含文档的_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进行此操作?

1 个答案:

答案 0 :(得分:0)

试试这个

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下的文档,这应该只修改数组中与查询匹配的第一个元素。