您可以为此使用$elemMatch运算符。首先让我们创建一个包含文档的集合-
> db.pushNewItemsDemo.insertOne( { "_id" :1, "StudentScore" : 56, "StudentOtherDetails" : [ { "StudentName" : "John", "StudentFriendName" : [ "Bob", "Carol" ] }, { "StudentName" : "David", "StudentFriendName" : [ "Mike", "Sam" ] } ] } ); { "acknowledged" : true, "insertedId" : 1 }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.pushNewItemsDemo.find();
这将产生以下输出-
{ "_id" : 1, "StudentScore" : 56, "StudentOtherDetails" : [ { "StudentName" : "John", "StudentFriendName" : [ "Bob", "Carol" ] }, { "StudentName" : "David", "StudentFriendName" : [ "Mike", "Sam" ] } ] }
以下是将新项目推送到对象内部数组的查询-
>db.pushNewItemsDemo.update({"_id":1,"StudentOtherDetails":{"$elemMatch":{"StudentName":"David"}}}, {"$push":{"StudentOtherDetails.$.StudentFriendName":"James"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们再次检查文件-
> db.pushNewItemsDemo.find();
这将产生以下输出-
{ "_id" : 1, "StudentScore" : 56, "StudentOtherDetails" : [ { "StudentName" : "John", "StudentFriendName" : [ "Bob", "Carol" ] }, { "StudentName" : "David", "StudentFriendName" : [ "Mike", "Sam", "James" ] } ] }