要使用MongoDB推送到数组中,请使用$push。让我们创建一个包含文档的集合-
> db.demo445.insertOne({"ListOfFriends":["Robert","Mike","Sam","Carol","David","Mike"]}); { "acknowledged" : true, "insertedId" : ObjectId("5e78f099bbc41e36cc3caec2") }
在find()方法的帮助下显示集合中的所有文档-
> db.demo445.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e78f099bbc41e36cc3caec2"), "ListOfFriends" : [ "Robert", "Mike", "Sam", "Carol", "David", "Mike" ] }
以下是推入数组的查询-
> db.demo445.update( ... { _id: ObjectId("5e78f099bbc41e36cc3caec2") }, ... { $push: { ListOfFriends: "Chris Brown" } } ... ) WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
在find()方法的帮助下显示集合中的所有文档-
> db.demo445.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5e78f099bbc41e36cc3caec2"), "ListOfFriends" : [ "Robert", "Mike", "Sam", "Carol", "David", "Mike", "Chris Brown" ] }