Mongodb 在文档中更新字段

Mongodb upsert field in document

我有一个格式如下的文档:

{ 
    "_id" : <id of document>, 
    "inventory" : [
        {
            "entity_id" : "<id>", 
            "ad_type" : "ADTYPE"
        }
    ]
}

我不确定这在 mongo 中是否可行,但我正在尝试对上述文档构建一个更新插入查询,如果库存不存在,我将插入一个空数组或推送到如果库存有一个或多个元素,则为数组。

我尝试使用 findAndModify 函数,但我认为这行不通。

db.collection.find({"_id":"value"}).forEach(
  function(doc){
    if(doc.hasOwnProperty('inventory'))
     {
       db.collection.update({"_id":doc._id},
       {"$push":{"inventory": "new value"}});
     }
   else
    {
       db.collection.update({"_id":doc._id},
       {"$set":{"inventory": new Array() }});
    }
  });

"collection"是数组,"subcollection"是对象。 该脚本将新字段 "rank" 添加到索引为 1 的数组元素。 如果字段不存在,脚本创建 "rank" 并设置值,如果字段存在,脚本更新值。

db.userCollection.update(
   { "_id": ObjectId("5a1e7aefd1928362e53c5c48"), 
     $and: [ { "collection.1.subcollection.id": "1234" }, 
        { "collection.1.rank": {"$ne": -1 }} 
       ] 
   },
   { $set: { "collection.1.rank": "5" } 
   }
)