您可以为此使用$addToSet运算符。首先让我们创建一个包含文档的集合-
> db.insertDataIntoArrayDemo.insertOne( { "UserDetails":[ { "UserId" :"user121", "userGroupMessage":[] }, { "UserId" :"user221", "userGroupMessage":["Cool","Good Morning"] } ] } ); { "acknowledged" : true, "insertedId" : ObjectId("5cd694e157806ebf1256f128") }
以下是在find()
方法的帮助下显示集合中所有文档的查询-
> db.insertDataIntoArrayDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd694e157806ebf1256f128"), "UserDetails" : [ { "UserId" : "user121", "userGroupMessage" : [ ] }, { "UserId" : "user221", "userGroupMessage" : [ "Cool", "Good Morning" ] } ] }
以下是将数据插入MongoDB的内部数组中的查询-
> db.insertDataIntoArrayDemo.update({"UserDetails.UserId":"user121"}, {"$addToSet":{"UserDetails.$.userGroupMessage":"Hello"}}); WriteResult({ "nMatched" : 1, "nUpserted" : 0, "nModified" : 1 })
让我们再次检查文档-
> db.insertDataIntoArrayDemo.find().pretty();
这将产生以下输出-
{ "_id" : ObjectId("5cd694e157806ebf1256f128"), "UserDetails" : [ { "UserId" : "user121", "userGroupMessage" : [ "Hello" ] }, { "UserId" : "user221", "userGroupMessage" : [ "Cool", "Good Morning" ] } ] }