2017-07-28 78 views
0

如何添加到陣列和更新,「最大」值。在一個聲明中

//Entry 1 (value 7) 

{ 
stuff : "goods" 
values : [7], 
max : 7, 
} 

//Entry 2 (value : 3) 

{ 
stuff : "goods" 
values : [7, 3], 
max : 7, 
} 

//Entry 3 (value : 9) 

{ 
stuff : "goods" 
values : [7, 3, 9], 
max : 9, 
} 

事情我已經試過

db.people.aggregate(
    {$match:{stuff:"goods"}}, 
    {$unwind:"$values"}, 
    {$max:1} 
    //lost ? {$set : {max : 1}} ?? 
); 

回答

1

.aggregate()方法僅僅是「查詢」數據,而實際上並沒有在數據庫中永久性地「修改」文檔。所以,你還是要.update()真正做出改變,而你閱讀$max不正確的文件,這是一個「不同的」操作員在「更新」實際應用:

因此,對於每次迭代:

db.people.drop(); 
db.people.update(
    { "stuff": "goods" }, 
    { 
    "$push": { "values": 7 }, 
    "$max": { "max": 7 } 
    }, 
    { "upsert": true } 
); 

// { "stuff": "goods", "values": [7], "max": 7 } 


db.people.update(
    { "stuff": "goods" }, 
    { 
    "$push": { "values": 3 }, 
    "$max": { "max": 3 } 
    }, 
    { "upsert": true } 
); 

// { "stuff": "goods", "values": [7,3], "max": 7 } 

db.people.update(
    { "stuff": "goods" }, 
    { 
    "$push": { "values": 9 }, 
    "$max": { "max": 9 } 
    }, 
    { "upsert": true } 
); 

// { "stuff": "goods", "values": [7,3,9], "max": 9 } 

因此,「該」版本的$max只會在文檔「when」中修改所提供的值「大於」現有屬性的當前值。當然$min是相反的。

雖然這兩個共享與「聚合管道」中使用的操作符相同,但它們實際上具有完全不同的功能。在這種情況下,這是你正在尋找的功能。

+0

真棒謝謝你。很有幫助的解釋! – stackoverflow