將值推入將多欄位設定為 TRUE 的陣列中?
要推送值,在將多欄位設定為 TRUE 時使用 $push 和 update()。我們使用文件建立一個集合 −
> db.demo747.insertOne({"CountryName":["US","IND"]}); { "acknowledged" : true, "insertedId" : ObjectId("5eae6a50a930c785c834e55f") } > db.demo747.insertOne({"CountryName":["UK","US"]}); { "acknowledged" : true, "insertedId" : ObjectId("5eae6a57a930c785c834e560") } > db.demo747.insertOne({"CountryName":["UK","IND"]}); { "acknowledged" : true, "insertedId" : ObjectId("5eae6a60a930c785c834e561") }
在集合中藉助 find() 方法顯示所有文件 −
> db.demo747.find();
將生成以下輸出 −
{ "_id" : ObjectId("5eae6a50a930c785c834e55f"), "CountryName" : [ "US", "IND" ] } { "_id" : ObjectId("5eae6a57a930c785c834e560"), "CountryName" : [ "UK", "US" ] } { "_id" : ObjectId("5eae6a60a930c785c834e561"), "CountryName" : [ "UK", "IND" ] }
以下是實現 update() 中 $push 的正確查詢 −
> db.demo747.update({},{$push:{CountryName:"AUS"}},{multi:true}); WriteResult({ "nMatched" : 3, "nUpserted" : 0, "nModified" : 3 })
在集合中藉助 find() 方法顯示所有文件 −
> db.demo747.find();
將生成以下輸出 −
{ "_id" : ObjectId("5eae6a50a930c785c834e55f"), "CountryName" : [ "US", "IND", "AUS" ] } { "_id" : ObjectId("5eae6a57a930c785c834e560"), "CountryName" : [ "UK", "US", "AUS" ] } { "_id" : ObjectId("5eae6a60a930c785c834e561"), "CountryName" : [ "UK", "IND", "AUS" ] }
廣告