若要仅将单个值添加到数组,请使用$push。首先让我们创建一个包含文档的集合-
> db.demo3.insertOne( ... { ... "Information" : { ... "Of" : { ... "StudentCode" : "STUDENT101", ... "StudentFavouriteSubject" : [ ... "MySQL", ... "Java" ... ] ... } ... } ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5e08b7ef25ddae1f53b6221b") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.demo3.find();
这将产生以下输出-
{ "_id" : ObjectId("5e08b7ef25ddae1f53b6221b"), "Information" : { "Of" : { "StudentCode" : "STUDENT101", "StudentFavouriteSubject" : [ "MySQL", "Java" ] } } }
这是仅向MongoDB中的数组添加单个值的查询-
> db.demo3.update({},{$push:{"Information.Of.StudentFavouriteSubject":"Spring and Hibernate"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们再次检查所有文件-
> db.demo3.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e08b7ef25ddae1f53b6221b"), "Information" : { "Of" : { "StudentCode" : "STUDENT101", "StudentFavouriteSubject" : [ "MySQL", "Java", "Spring and Hibernate" ] } } }