您可以
db.test.update(
{ _id : 133 },
{ $set : { PackSizes: {_id: 123, PackSizeName:"xyz", UnitName:"pqr"}} }
)
PackSizes做它可以是任何文件,以陣列或沒有它。
你的結果文件將
{
"_id" : 133,
"Name" : "abc",
"Price" : 20,
"PackSizes" : {
"_id" : 123,
"PackSizeName" : "xyz",
"UnitName" : "pqr"
}
}
更新時間: 對於增加新的領域和陣列成員,
假設我們有原始文檔
{
_id: 133,
Name: "abc",
Price: 20
}
第1步:添加新字段:PackSizes是一個陣列
db.test.update(
{ _id : 133 },
{ $set : {PackSizes: [ {_id: 123, PackSizeName:"xyz", UnitName:"pqr"}]}}
)
第2步:推新項目陣列
db.test.update(
{ _id : 133 },
{ $push : { PackSizes: {_id: 124, PackSizeName:"xyz", UnitName:"pqr"}} }
)
,你將有
{
"_id" : 133,
"Name" : "abc",
"Price" : 20,
"PackSizes" : [
{
"_id" : 123,
"PackSizeName" : "xyz",
"UnitName" : "pqr"
},
{
"_id" : 124,
"PackSizeName" : "xyz",
"UnitName" : "pqr"
}
]
}
處理器謝謝。您能否告訴我如何將PackSize添加到PackSizes []字段? –
db.test.update( {_id:133}, {$ push:{PackSizes:{_id:124,PackSizeName:「xyz」,UnitName:「pqr」}}} – Disposer
它創建一個錯誤 - The字段'PackSizes'必須是一個數組,但是類型爲Object ... –