在MongoDB中使用$push
让我们创建一个包含文档的集合-
> db.demo738.insertOne({Subjects:["C","C++"]}); { "acknowledged" : true, "insertedId" : ObjectId("5ead696557bb72a10bcf0661") } > db.demo738.insertOne({Subjects:["MySQL","PL/SQL"]}); { "acknowledged" : true, "insertedId" : ObjectId("5ead696657bb72a10bcf0662") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo738.find();
这将产生以下输出-
{ "_id" : ObjectId("5ead696557bb72a10bcf0661"), "Subjects" : [ "C", "C++" ] } { "_id" : ObjectId("5ead696657bb72a10bcf0662"), "Subjects" : [ "MySQL", "PL/SQL" ] }
以下是要推送的查询-
>db.demo738.update({_id:ObjectId("5ead696657bb72a10bcf0662")},{$push:{"Subjects":"MongoDB"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在find()方法的帮助下显示集合中的所有文档-
> db.demo738.find();
这将产生以下输出-
{ "_id" : ObjectId("5ead696557bb72a10bcf0661"), "Subjects" : [ "C", "C++" ] } { "_id" : ObjectId("5ead696657bb72a10bcf0662"), "Subjects" : [ "MySQL", "PL/SQL", "MongoDB" ] }