2017-05-17 14 views
0

這是我擁有的對象:如何在子文檔中更新子文檔並刪除單個數組對象?

{ 
    "_id": ObjectId("590985b1859aefea4a39982f"), 
    "comment": [{ 
    "created_at": 1493880257678.0, 
    "comment": "12345", 
    "user_id": ObjectId("58edd98d40627c492c8689c5"), 
    "_id": ObjectId("590acdc1141b16c6521b9140"), 
    "modified": 1493880257678.0, 
    "assigned_to": null 
    }, { 
    "created_at": 1493880257678.0, 
    "comment": "12345", 
    "user_id": ObjectId("5906c50c1be98711121edf2b"), 
    "_id": ObjectId("590acdc1141b16c6521b9140"), 
    "modified": 1493880257678.0, 
    "assigned_to": null 
    }, { 
    "created_at": 1493880257678.0, 
    "comment": "12345", 
    "user_id": ObjectId("58edd98d40627c492c8689c5"), 
    "_id": ObjectId("590acdc1141b16c6521b9140"), 
    "modified": 1493880257678.0, 
    "assigned_to": null 
    }] 
} 

我想刪除評論的子文檔,其中user_id(58edd98d40627c492c8689c5)

+0

您可以編輯的問題是_a小neater_? – evolutionxbox

回答

1

可以使用findOneAndUpdate與$pull

你會構建你的這樣的查詢。

findOneAndUpdate(
{_id: <id of the document>}, 
{$pull: {comment: {user_id: <user_id>}}}, 
{multi:true} 
) 

不知道你用的是什麼客戶端或驅動程序,但這裏是我的robomongo做了一個例子測試,集合名稱爲「文件」

db.getCollection('documents').findOneAndUpdate(
{_id: new ObjectId("590985b1859aefea4a39982f")}, 
{$pull: 
    {comment:{user_id : new ObjectId("58edd98d40627c492c8689c5")}} 
}, 
multi:true})