要将文档推送到数组中,请使用$push和update()
。让我们创建一个包含文档的集合-
>db.demo310.insertOne({"Name":"Chris","details":[{"Id":101,"Subject":"MySQL"},{"Id":102,"Subject":"MongoDB"}]}); { "acknowledged" : true, "insertedId" : ObjectId("5e50cabdf8647eb59e562043") }
在find()
方法的帮助下显示集合中的所有文档-
> db.demo310.find();
这将产生以下输出-
{ "_id" : ObjectId("5e50cabdf8647eb59e562043"), "Name" : "Chris", "details" : [ { "Id" : 101, "Subject" : "MySQL" }, { "Id" : 102, "Subject" : "MongoDB" } ] }
以下是查询以推送文档-
> db.demo310.update({ _id:ObjectId("5e50cabdf8647eb59e562043")}, ...{ $push: {"details": { ... "Id" : 103, ... "Subject": "Java" ... }} ...} ...) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在find()
方法的帮助下显示集合中的所有文档-
> db.demo310.find();
这将产生以下输出-
{ "_id" : ObjectId("5e50cabdf8647eb59e562043"), "Name" : "Chris", "details" : [ { "Id" : 101, "Subject" : "MySQL" }, { "Id" : 102, "Subject" : "MongoDB" }, { "Id" : 103, "Subject" : "Java" } ] }