要推送值,请将$push与update()一起使用,并将多字段设置为TRUE。让我们创建一个包含文档的集合-
> 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" ] }