2014-11-03 71 views
1

如果我有一個具有包含代表一天計數,或許像一個元素的數組一個文檔: -如何在更新查詢中添加或包含數組?

{ 
    data : [ {'20141102' : 2 },{'20141103' : 4 } ] 
} 

當我做一個更新,我有一個字符串'20141103'再後來'20141104'我想要增加數組條目或添加一個新的數組條目。這是可能的更新?

回答

3

是的,這是可行的。我試過像這樣:
(在mongo shell上運行;客戶端和服務器都是V2.6.4)

function tryAndFine(coll, key, value) { 
    var entry = {}; 
    entry[key] = value; 

    var parent = 'data'; 
    var prefix = parent + '.'; 

    function incrementOnly() { 
     var criteria = {}; 
     criteria[prefix + key] = {$exists : true}; 

     var update = {}; 
     update[prefix + "$." + key] = value; 

     var result = coll.update(criteria, {$inc : update}); 
     // if increment fails, try to add a new one 
     if (result.nModified == 0) { 
      addNewElement(); 
     } 
    } 

    function addNewElement() { 
     var criteria = {}; 
     criteria[prefix + key] = {$exists : false}; 

     var update = {}; 
     update[parent] = entry; 

     var result = coll.update(criteria, {$push : update}, {upsert : true}); 
     // if exists, try to increment the count 
     if (result.upserted == 0 && result.nModified == 0) { 
      incrementOnly(); 
     } 
    } 

    // run entry 
    incrementOnly(); 
} 

// test 
var c = db.c; 
c.drop(); 
tryAndFine(c, '20141103', 1); 
tryAndFine(c, '20141103', 1); 
tryAndFine(c, '20141104', 1); 
tryAndFine(c, '20141105', 1); 
tryAndFine(c, '20141104', 1); 

// output 
{ 
    "_id" : ObjectId("54577e1a3502852bd4ad2395"), 
    "data" : [ { 
     "20141103" : 2 
    }, { 
     "20141104" : 2 
    }, { 
     "20141105" : 1 
    } ] 
}