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" ] } ] }
广告