使用$push运算符添加子文档。首先让我们创建一个包含文档的集合-
> db.subDocumentToSubDocumentDemo.insertOne( { "_id" :101, "StudentName" : "Larry", "StudentAge" : 21, "StudentDetails" : [ { "StudentCountryName" : "US", "StudentFavouriteSubjectList" : [ ] } ] } ); { "acknowledged" : true, "insertedId" : 101 }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.subDocumentToSubDocumentDemo.find().pretty();
这将产生以下输出-
{ "_id" : 101, "StudentName" : "Larry", "StudentAge" : 21, "StudentDetails" : [ { "StudentCountryName" : "US", "StudentFavouriteSubjectList" : [ ] } ] }
以下是将子文档添加到MongoDB中的子文档数组的查询-
> db.subDocumentToSubDocumentDemo.update( { "_id": 101 }, { "$push": { "StudentDetails": { "StudentCountryName" : "UK", "StudentFavouriteSubjectList" : ["MongoDB","Java" ] } } } ); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们再次检查所有文件-
> db.subDocumentToSubDocumentDemo.find().pretty();
这将产生以下输出-
{ "_id" : 101, "StudentName" : "Larry", "StudentAge" : 21, "StudentDetails" : [ { "StudentCountryName" : "US", "StudentFavouriteSubjectList" : [ ] }, { "StudentCountryName" : "UK", "StudentFavouriteSubjectList" : [ "MongoDB", "Java" ] } ] }