簡體   English   中英

更新文檔MongoDB PHP的價值

[英]Updating value of a document MongoDB PHP

在一個名為user_notifications的數據庫中,每個用戶都有一個帶有其用戶ID的集合。

應該有一個靜態文檔,其中包含每個集合的默認設置為0的計數器列。

在一個簡單的方法調用中,我需要將計數器的值增加1,作為MongoDB中的新手,我認為我搞砸了。 需要一些想法,這是我的對象可以做到的:

private function increment_notification()
{

    // database   => notification
    // collection => _238
    // document   => unseen_counter

    $unseen = $this->notification->_238->unseen_counter; // selecting a single document

    // if the document didn't exists then create the document and 
    // set a default value 0 to the counter row.

    if(!$unseen) {
        // create a new document
        $this->notification->insertOne([
            '_id' => 'unseen_counter',
            'counter' => '0'
        ]);
    } else {
        // we already have the document
        // now update the counter value by 1
        $unseen->update([
            '$set' => [
                'counter' => $unseen['counter'] + 1;
            ]
        ]);
    }
}

我最終將此方法編寫為偽代碼:[

作為MongoDB的初學者,我的架構設計如何? 有什么建議可以使它更好嗎? 另外,我應該如何運行上述查詢?

謝謝

另一種方法是使用$inc運算符。 這是$inc 文檔和示例

暫無
暫無

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

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