簡體   English   中英

在MongoDB中插入/插入嵌套文檔

[英]In-/upserting a nested document in MongoDB

我正在嘗試以類似於以下內容的結構來插入嵌套文檔(活動)

{
  "_id" : "123",
  "modules" : {
    "x" : {
    },
    "y" : {
      "activities" : {
        "preview": {
          "createdAt": "2014-10-13 15:21:22.113",
          "data": {}
        }
      }
    },
    "z" : {
      "activities" : {
        "render": {
          "createdAt": "2014-10-15 04:22:25.171",
          "data": {}
        },
        "render": {
          "createdAt": "2014-10-14 02:42:24.132",
          "data": {}
        }
      }
    }
  }
}

然后我嘗試

selector = { "_id": id, "modules": module, "activities" }
activity = { "preview": { "data": data }}
Meteor.users.upsert(selector, { $set: activity, $setOnInsert: { "createdAt: new Date()" }})

哪個產量

MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: meteor.users.$_id_  dup key: { : "123" }

_id是唯一的索引鍵。 每個用戶的_id “級別”上以及每個模塊的activities “級別”上還有其他字段/文檔,但沒有關於upsert的字段/文檔。 每個模塊都是唯一的。 在插入第一個記錄之前,活動文檔不存在。

借此,我希望有人能掌握我要完成的目標,並能向正確的方向提供幫助。

Upsert用於插入或更新(如果存在)新文檔。 它不適用於子文檔。

您應該只更新文檔:

selector = { "_id": id, "modules": module, preview : null }
activity = { "preview": { "data": data , "createdAt" : new Date() }}
Meteor.users.update(selector, { $set: 'activity' : activity }})

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM