簡體   English   中英

MongoDB:更新子文檔中的特定數組元素

[英]MongoDB: Updating A specific array element in a sub document

我是mongodb的新手,所以如果問題有點基本,請原諒。 我有一個具有相對復雜的文檔結構的mongo集合。 這些文檔包含子文檔和數組。 我需要向此集合中的某些文檔中添加其他數據。 該文檔的簡化版本為:

    "date" : ISODate("2018-08-07T08:00:00.000+0000"), 
    .
    . <<-- Other fields
    .
    "basket" : 
   [
     {
            "assetId" : NumberInt(639), 
            "securityId" : NumberInt(12470), 
            .
            . <<-- Other fields
            .
            "exGroup" : [
                . << -- Fields......
                .
                . << -- New Data will go here
            ]
     }
     .
     . << More elements

   ]

以下(摘要)聚合查詢查找需要修改的文檔:

   { 
        "$match" : {
            "date" : {
                "$gte" : ISODate("2018-08-07T00:00:00.000+0000"), 
                "$lt" : ISODate("2018-08-08T00:00:00.000+0000")
            }
        }
    }, 
    { 
        "$unwind" : {
            "path" : "$basket"
        }
    }, 
    { 
        "$unwind" : {
            "path" : "$basket.exGroup"
        }
    }, 
    { 
        "$project" : {
            "_id" : 1.0, 
            "date" : 1.0, 
            "assetId" : "$basket.assetId", 
            "securityId" : "$basket.securityId", 
            "exGroup" : "$basket.exGroup"
        }
    }, 
    { 
        "$unwind" : {
            "path" : "$exGroup"
        }
    }, 
    { 
        "$match" : {
            "exGroup.order" : {
                "$exists" : true
            }
        }
    }

對於mongo查詢返回的每個文檔,我需要(在python中)從SQL數據庫中檢索一組附加數據,然后將此數據附加到原始mongo文檔中,如上所示。 新字段的集合將相同,數據將不同。 對我來說還不清楚的是,一旦獲得數據,我將如何更新數組值。

有人可以給我指點嗎?

試試這個,對我有用!

mySchema.aggregate([
   //your aggregation code
],function(err, docList){
  //for each doc in docList
  async.each(docList, function(doc, callback){
    query = {$and:[{idField:doc.idField},{"myArray.ArrayId":doc.myArray.ArrayId}]}
    //Update or create field in array
    update = {$set:"myArray.$.FieldNameToCreateOrUpdate":value}}
    projection = {field1:1, field2:1, field3:1}
    mySchema.findOneAndUpdate(query, update, projection, function(err, done){
        if(err){callback(err,null)}
        callback(null,'done')
    })
  ,function(err){
    //code if error
    //code if no error
  }
})

暫無
暫無

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

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