MongoDB查询将文档添加到已创建的集合中
要将文档添加到已创建的集合中,请在MongoDB中使用$push。让我们创建一个包含文档的集合-
> db.demo177.insertOne( { "Id": "101", "details": [ { "StudentName": "Chris", "Scores": [67, 71, 74], "SubjectName": ["MySQL", "Java"] }, { "StudentName": "David", "Scores": [89,98,45], "SubjectName": ["PL/SQL", "C"] } ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5e384b2b9e4f06af551997f4") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo177.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e384b2b9e4f06af551997f4"), "Id" : "101", "details" : [ { "StudentName" : "Chris", "Scores" : [ 67, 71, 74 ], "SubjectName" : [ "MySQL", "Java" ] }, { "StudentName" : "David", "Scores" : [ 89, 98, 45 ], "SubjectName" : [ "PL/SQL", "C" ] } ] }
以下是在已创建的集合中添加文档的查询-
> db.demo177.update({"Id": "101"}, ...{ ... $push: { ... "details": { ... "StudentName": "Chris", ... "Scores": [90, 91, 94], ... "SubjectName": ["MongoDB", "SQL Server"] ... } ... } ...}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在find()方法的帮助下显示集合中的所有文档-
> db.demo177.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e384b2b9e4f06af551997f4"), "Id" : "101", "details" : [ { "StudentName" : "Chris", "Scores" : [ 67, 71, 74 ], "SubjectName" : [ "MySQL", "Java" ] }, { "StudentName" : "David", "Scores" : [ 89, 98, 45 ], "SubjectName" : [ "PL/SQL", "C" ] }, { "StudentName" : "Chris", "Scores" : [ 90, 91, 94 ], "SubjectName" : [ "MongoDB", "SQL Server" ] } ] }