2017-11-18 72 views
0

我是mongoDB中的新成員,所以我需要一些幫助。
我有一個備份集合。它包含以下數據文件:在不刪除的情況下更新MongoDB集合中的某些文檔

{ 
    "_id" : ObjectId("59f18942e7798954dc373b67"), 
    "category" : "building", 
}, 
{ 
    "_id" : ObjectId("59f18942e7798954dc373b68"), 
    "category" : "building", 
}, 
{ 
    "_id" : ObjectId("59f18942e7798954dc373b69"), 
    "category" : "tree", 
    "type" : 18, 
}, 
{ 
    "_id" : ObjectId("59f18942e7798954dc373b70"), 
    "category" : "book", 
    "type" : 18, 
} 

然後,例如,某些對象發生了變化,成爲這樣的:

{ 
    "_id" : ObjectId("59f18942e7798954dc373b67"), 
    "category" : "building", 
    "size" : 100 
}, 
{ 
    "_id" : ObjectId("59f18942e7798954dc373b68"), 
    "category" : "building", 
    "size" : 400 
}, 
{ 
    "_id" : ObjectId("59f18942e7798954dc373b70"), 
    "category" : "book", 
    "type" : 18, 
    "title" : "New" 
} 

所以我需要在我的數據庫更新它們。正如我所理解的那樣,請替換。我已閱讀關於使用'upsert'和'multi'的文檔。但我無法實現它。
如何做到這一點?

+1

向我們展示你已經嘗試了什麼,發生了什麼和在那裏你就完蛋了。 –

+1

此外,請查看文檔:https://docs.mongodb.com/php-library/current/tutorial/crud/#update-one-document –

+0

我已閱讀此文檔。但是,據我所知,我只能替換一個文件,但不是我需要的全部文件(例如,一個查詢中有3個文件)。我對嗎? –

回答

0

在蒙戈更新文件的基本語法是

db.collection.update(query,update,options); 

對於你的問題,

1. db.collection.update({_id: ObjectId("59f18942e7798954dc373b67")},{$set:{size:100}});

2. db.collection.update({_id: ObjectId("59f18942e7798954dc373b68")},{$set:{size:400}});

3. db.collection.update({_id: ObjectId("59f18942e7798954dc373b70")},{$set:{title:"New"}});

編輯:

你可以試試這個,如果你想在一個命令執行寫操作:

> db.characters.bulkWrite(
>  [ 
>   { updateOne : 
>    { 
>    "filter" : { _id : ObjectId("59f18942e7798954dc373b67") }, 
>    "update" : { $set : { size : 100 } } 
>    } 
>   }, 
>   { updateOne : 
>    { 
>    "filter" : { _id : ObjectId("59f18942e7798954dc373b68") }, 
>    "update" : { $set : { size : 400 } } 
>    } 
>   }, 
>   { updateOne : 
>    { 
>    "filter" : { _id : ObjectId("59f18942e7798954dc373b68") }, 
>    "update" : { $set: { title: "New"} } 
>    } 
>   }, 
>  ]  
>); 
+0

是的,我可以在3個查詢中實現它,但我想要在一個查詢中完成。你可以幫我嗎? –

+0

O,謝謝!另外我還有一個問題。據我從文檔中瞭解到,多次替換對新的mongoDB驅動程序是嚴格的?所以我也不能在一個查詢中使用$ pull/$ push for php? –

+0

你不能在同一個查詢中使用兩個,因爲我知道..但我不確定。 此外,如果這個答案幫助你,然後請將其標記爲正確的答案。 –

相關問題